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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Kronuz/pyScss | scss/extension/compass/images.py | image_height | def image_height(image):
"""
Returns the height of the image found at the path supplied by `image`
relative to your project's images directory.
"""
image_size_cache = _get_cache('image_size_cache')
if not Image:
raise SassMissingDependency('PIL', 'image manipulation')
filepath = String.unquoted(image).value
path = None
try:
height = image_size_cache[filepath][1]
except KeyError:
height = 0
IMAGES_ROOT = _images_root()
if callable(IMAGES_ROOT):
try:
_file, _storage = list(IMAGES_ROOT(filepath))[0]
except IndexError:
pass
else:
path = _storage.open(_file)
else:
_path = os.path.join(IMAGES_ROOT, filepath.strip(os.sep))
if os.path.exists(_path):
path = open(_path, 'rb')
if path:
image = Image.open(path)
size = image.size
height = size[1]
image_size_cache[filepath] = size
return Number(height, 'px') | python | def image_height(image):
"""
Returns the height of the image found at the path supplied by `image`
relative to your project's images directory.
"""
image_size_cache = _get_cache('image_size_cache')
if not Image:
raise SassMissingDependency('PIL', 'image manipulation')
filepath = String.unquoted(image).value
path = None
try:
height = image_size_cache[filepath][1]
except KeyError:
height = 0
IMAGES_ROOT = _images_root()
if callable(IMAGES_ROOT):
try:
_file, _storage = list(IMAGES_ROOT(filepath))[0]
except IndexError:
pass
else:
path = _storage.open(_file)
else:
_path = os.path.join(IMAGES_ROOT, filepath.strip(os.sep))
if os.path.exists(_path):
path = open(_path, 'rb')
if path:
image = Image.open(path)
size = image.size
height = size[1]
image_size_cache[filepath] = size
return Number(height, 'px') | [
"def",
"image_height",
"(",
"image",
")",
":",
"image_size_cache",
"=",
"_get_cache",
"(",
"'image_size_cache'",
")",
"if",
"not",
"Image",
":",
"raise",
"SassMissingDependency",
"(",
"'PIL'",
",",
"'image manipulation'",
")",
"filepath",
"=",
"String",
".",
"un... | Returns the height of the image found at the path supplied by `image`
relative to your project's images directory. | [
"Returns",
"the",
"height",
"of",
"the",
"image",
"found",
"at",
"the",
"path",
"supplied",
"by",
"image",
"relative",
"to",
"your",
"project",
"s",
"images",
"directory",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/compass/images.py#L258-L289 | train | 23,100 |
Kronuz/pyScss | scss/source.py | SourceFile.path | def path(self):
"""Concatenation of ``origin`` and ``relpath``, as a string. Used in
stack traces and other debugging places.
"""
if self.origin:
return six.text_type(self.origin / self.relpath)
else:
return six.text_type(self.relpath) | python | def path(self):
"""Concatenation of ``origin`` and ``relpath``, as a string. Used in
stack traces and other debugging places.
"""
if self.origin:
return six.text_type(self.origin / self.relpath)
else:
return six.text_type(self.relpath) | [
"def",
"path",
"(",
"self",
")",
":",
"if",
"self",
".",
"origin",
":",
"return",
"six",
".",
"text_type",
"(",
"self",
".",
"origin",
"/",
"self",
".",
"relpath",
")",
"else",
":",
"return",
"six",
".",
"text_type",
"(",
"self",
".",
"relpath",
")... | Concatenation of ``origin`` and ``relpath``, as a string. Used in
stack traces and other debugging places. | [
"Concatenation",
"of",
"origin",
"and",
"relpath",
"as",
"a",
"string",
".",
"Used",
"in",
"stack",
"traces",
"and",
"other",
"debugging",
"places",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/source.py#L125-L132 | train | 23,101 |
Kronuz/pyScss | scss/source.py | SourceFile.from_filename | def from_filename(cls, path_string, origin=MISSING, **kwargs):
""" Read Sass source from a String specifying the path
"""
path = Path(path_string)
return cls.from_path(path, origin, **kwargs) | python | def from_filename(cls, path_string, origin=MISSING, **kwargs):
""" Read Sass source from a String specifying the path
"""
path = Path(path_string)
return cls.from_path(path, origin, **kwargs) | [
"def",
"from_filename",
"(",
"cls",
",",
"path_string",
",",
"origin",
"=",
"MISSING",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"Path",
"(",
"path_string",
")",
"return",
"cls",
".",
"from_path",
"(",
"path",
",",
"origin",
",",
"*",
"*",
"kwa... | Read Sass source from a String specifying the path | [
"Read",
"Sass",
"source",
"from",
"a",
"String",
"specifying",
"the",
"path"
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/source.py#L194-L198 | train | 23,102 |
Kronuz/pyScss | scss/source.py | SourceFile.from_file | def from_file(cls, f, origin=MISSING, relpath=MISSING, **kwargs):
"""Read Sass source from a file or file-like object.
If `origin` or `relpath` are missing, they are derived from the file's
``.name`` attribute as with `from_path`. If it doesn't have one, the
origin becomes None and the relpath becomes the file's repr.
"""
contents = f.read()
encoding = determine_encoding(contents)
if isinstance(contents, six.binary_type):
contents = contents.decode(encoding)
if origin is MISSING or relpath is MISSING:
filename = getattr(f, 'name', None)
if filename is None:
origin = None
relpath = repr(f)
else:
origin, relpath = cls._key_from_path(Path(filename), origin)
return cls(origin, relpath, contents, encoding=encoding, **kwargs) | python | def from_file(cls, f, origin=MISSING, relpath=MISSING, **kwargs):
"""Read Sass source from a file or file-like object.
If `origin` or `relpath` are missing, they are derived from the file's
``.name`` attribute as with `from_path`. If it doesn't have one, the
origin becomes None and the relpath becomes the file's repr.
"""
contents = f.read()
encoding = determine_encoding(contents)
if isinstance(contents, six.binary_type):
contents = contents.decode(encoding)
if origin is MISSING or relpath is MISSING:
filename = getattr(f, 'name', None)
if filename is None:
origin = None
relpath = repr(f)
else:
origin, relpath = cls._key_from_path(Path(filename), origin)
return cls(origin, relpath, contents, encoding=encoding, **kwargs) | [
"def",
"from_file",
"(",
"cls",
",",
"f",
",",
"origin",
"=",
"MISSING",
",",
"relpath",
"=",
"MISSING",
",",
"*",
"*",
"kwargs",
")",
":",
"contents",
"=",
"f",
".",
"read",
"(",
")",
"encoding",
"=",
"determine_encoding",
"(",
"contents",
")",
"if"... | Read Sass source from a file or file-like object.
If `origin` or `relpath` are missing, they are derived from the file's
``.name`` attribute as with `from_path`. If it doesn't have one, the
origin becomes None and the relpath becomes the file's repr. | [
"Read",
"Sass",
"source",
"from",
"a",
"file",
"or",
"file",
"-",
"like",
"object",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/source.py#L201-L221 | train | 23,103 |
Kronuz/pyScss | scss/source.py | SourceFile.from_string | def from_string(cls, string, relpath=None, encoding=None, is_sass=None):
"""Read Sass source from the contents of a string.
The origin is always None. `relpath` defaults to "string:...".
"""
if isinstance(string, six.text_type):
# Already decoded; we don't know what encoding to use for output,
# though, so still check for a @charset.
# TODO what if the given encoding conflicts with the one in the
# file? do we care?
if encoding is None:
encoding = determine_encoding(string)
byte_contents = string.encode(encoding)
text_contents = string
elif isinstance(string, six.binary_type):
encoding = determine_encoding(string)
byte_contents = string
text_contents = string.decode(encoding)
else:
raise TypeError("Expected text or bytes, got {0!r}".format(string))
origin = None
if relpath is None:
m = hashlib.sha256()
m.update(byte_contents)
relpath = repr("string:{0}:{1}".format(
m.hexdigest()[:16], text_contents[:100]))
return cls(
origin, relpath, text_contents, encoding=encoding,
is_sass=is_sass,
) | python | def from_string(cls, string, relpath=None, encoding=None, is_sass=None):
"""Read Sass source from the contents of a string.
The origin is always None. `relpath` defaults to "string:...".
"""
if isinstance(string, six.text_type):
# Already decoded; we don't know what encoding to use for output,
# though, so still check for a @charset.
# TODO what if the given encoding conflicts with the one in the
# file? do we care?
if encoding is None:
encoding = determine_encoding(string)
byte_contents = string.encode(encoding)
text_contents = string
elif isinstance(string, six.binary_type):
encoding = determine_encoding(string)
byte_contents = string
text_contents = string.decode(encoding)
else:
raise TypeError("Expected text or bytes, got {0!r}".format(string))
origin = None
if relpath is None:
m = hashlib.sha256()
m.update(byte_contents)
relpath = repr("string:{0}:{1}".format(
m.hexdigest()[:16], text_contents[:100]))
return cls(
origin, relpath, text_contents, encoding=encoding,
is_sass=is_sass,
) | [
"def",
"from_string",
"(",
"cls",
",",
"string",
",",
"relpath",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"is_sass",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",
"# Already decoded; we don't know ... | Read Sass source from the contents of a string.
The origin is always None. `relpath` defaults to "string:...". | [
"Read",
"Sass",
"source",
"from",
"the",
"contents",
"of",
"a",
"string",
"."
] | fb32b317f6e2b4b4aad2b86a74844658ac4aa11e | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/source.py#L224-L256 | train | 23,104 |
bitcraft/pyscroll | pyscroll/quadtree.py | FastQuadTree.hit | def hit(self, rect):
"""Returns the items that overlap a bounding rectangle.
Returns the set of all items in the quad-tree that overlap with a
bounding rectangle.
@param rect:
The bounding rectangle being tested against the quad-tree. This
must possess left, top, right and bottom attributes.
"""
# Find the hits at the current level.
hits = {tuple(self.items[i]) for i in rect.collidelistall(self.items)}
# Recursively check the lower quadrants.
if self.nw and rect.left <= self.cx and rect.top <= self.cy:
hits |= self.nw.hit(rect)
if self.sw and rect.left <= self.cx and rect.bottom >= self.cy:
hits |= self.sw.hit(rect)
if self.ne and rect.right >= self.cx and rect.top <= self.cy:
hits |= self.ne.hit(rect)
if self.se and rect.right >= self.cx and rect.bottom >= self.cy:
hits |= self.se.hit(rect)
return hits | python | def hit(self, rect):
"""Returns the items that overlap a bounding rectangle.
Returns the set of all items in the quad-tree that overlap with a
bounding rectangle.
@param rect:
The bounding rectangle being tested against the quad-tree. This
must possess left, top, right and bottom attributes.
"""
# Find the hits at the current level.
hits = {tuple(self.items[i]) for i in rect.collidelistall(self.items)}
# Recursively check the lower quadrants.
if self.nw and rect.left <= self.cx and rect.top <= self.cy:
hits |= self.nw.hit(rect)
if self.sw and rect.left <= self.cx and rect.bottom >= self.cy:
hits |= self.sw.hit(rect)
if self.ne and rect.right >= self.cx and rect.top <= self.cy:
hits |= self.ne.hit(rect)
if self.se and rect.right >= self.cx and rect.bottom >= self.cy:
hits |= self.se.hit(rect)
return hits | [
"def",
"hit",
"(",
"self",
",",
"rect",
")",
":",
"# Find the hits at the current level.",
"hits",
"=",
"{",
"tuple",
"(",
"self",
".",
"items",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"rect",
".",
"collidelistall",
"(",
"self",
".",
"items",
")",
"}",
... | Returns the items that overlap a bounding rectangle.
Returns the set of all items in the quad-tree that overlap with a
bounding rectangle.
@param rect:
The bounding rectangle being tested against the quad-tree. This
must possess left, top, right and bottom attributes. | [
"Returns",
"the",
"items",
"that",
"overlap",
"a",
"bounding",
"rectangle",
"."
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/quadtree.py#L105-L129 | train | 23,105 |
bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer.scroll | def scroll(self, vector):
""" scroll the background in pixels
:param vector: (int, int)
"""
self.center((vector[0] + self.view_rect.centerx,
vector[1] + self.view_rect.centery)) | python | def scroll(self, vector):
""" scroll the background in pixels
:param vector: (int, int)
"""
self.center((vector[0] + self.view_rect.centerx,
vector[1] + self.view_rect.centery)) | [
"def",
"scroll",
"(",
"self",
",",
"vector",
")",
":",
"self",
".",
"center",
"(",
"(",
"vector",
"[",
"0",
"]",
"+",
"self",
".",
"view_rect",
".",
"centerx",
",",
"vector",
"[",
"1",
"]",
"+",
"self",
".",
"view_rect",
".",
"centery",
")",
")"
... | scroll the background in pixels
:param vector: (int, int) | [
"scroll",
"the",
"background",
"in",
"pixels"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L87-L93 | train | 23,106 |
bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer.center | def center(self, coords):
""" center the map on a pixel
float numbers will be rounded.
:param coords: (number, number)
"""
x, y = round(coords[0]), round(coords[1])
self.view_rect.center = x, y
mw, mh = self.data.map_size
tw, th = self.data.tile_size
vw, vh = self._tile_view.size
# prevent camera from exposing edges of the map
if self.clamp_camera:
self._anchored_view = True
self.view_rect.clamp_ip(self.map_rect)
x, y = self.view_rect.center
# calc the new position in tiles and pixel offset
left, self._x_offset = divmod(x - self._half_width, tw)
top, self._y_offset = divmod(y - self._half_height, th)
right = left + vw
bottom = top + vh
if not self.clamp_camera:
# not anchored, so the rendered map is being offset by values larger
# than the tile size. this occurs when the edges of the map are inside
# the screen. a situation like is shows a background under the map.
self._anchored_view = True
dx = int(left - self._tile_view.left)
dy = int(top - self._tile_view.top)
if mw < vw or left < 0:
left = 0
self._x_offset = x - self._half_width
self._anchored_view = False
elif right > mw:
left = mw - vw
self._x_offset += dx * tw
self._anchored_view = False
if mh < vh or top < 0:
top = 0
self._y_offset = y - self._half_height
self._anchored_view = False
elif bottom > mh:
top = mh - vh
self._y_offset += dy * th
self._anchored_view = False
# adjust the view if the view has changed without a redraw
dx = int(left - self._tile_view.left)
dy = int(top - self._tile_view.top)
view_change = max(abs(dx), abs(dy))
if view_change and (view_change <= self._redraw_cutoff):
self._buffer.scroll(-dx * tw, -dy * th)
self._tile_view.move_ip(dx, dy)
self._queue_edge_tiles(dx, dy)
self._flush_tile_queue(self._buffer)
elif view_change > self._redraw_cutoff:
logger.info('scrolling too quickly. redraw forced')
self._tile_view.move_ip(dx, dy)
self.redraw_tiles(self._buffer) | python | def center(self, coords):
""" center the map on a pixel
float numbers will be rounded.
:param coords: (number, number)
"""
x, y = round(coords[0]), round(coords[1])
self.view_rect.center = x, y
mw, mh = self.data.map_size
tw, th = self.data.tile_size
vw, vh = self._tile_view.size
# prevent camera from exposing edges of the map
if self.clamp_camera:
self._anchored_view = True
self.view_rect.clamp_ip(self.map_rect)
x, y = self.view_rect.center
# calc the new position in tiles and pixel offset
left, self._x_offset = divmod(x - self._half_width, tw)
top, self._y_offset = divmod(y - self._half_height, th)
right = left + vw
bottom = top + vh
if not self.clamp_camera:
# not anchored, so the rendered map is being offset by values larger
# than the tile size. this occurs when the edges of the map are inside
# the screen. a situation like is shows a background under the map.
self._anchored_view = True
dx = int(left - self._tile_view.left)
dy = int(top - self._tile_view.top)
if mw < vw or left < 0:
left = 0
self._x_offset = x - self._half_width
self._anchored_view = False
elif right > mw:
left = mw - vw
self._x_offset += dx * tw
self._anchored_view = False
if mh < vh or top < 0:
top = 0
self._y_offset = y - self._half_height
self._anchored_view = False
elif bottom > mh:
top = mh - vh
self._y_offset += dy * th
self._anchored_view = False
# adjust the view if the view has changed without a redraw
dx = int(left - self._tile_view.left)
dy = int(top - self._tile_view.top)
view_change = max(abs(dx), abs(dy))
if view_change and (view_change <= self._redraw_cutoff):
self._buffer.scroll(-dx * tw, -dy * th)
self._tile_view.move_ip(dx, dy)
self._queue_edge_tiles(dx, dy)
self._flush_tile_queue(self._buffer)
elif view_change > self._redraw_cutoff:
logger.info('scrolling too quickly. redraw forced')
self._tile_view.move_ip(dx, dy)
self.redraw_tiles(self._buffer) | [
"def",
"center",
"(",
"self",
",",
"coords",
")",
":",
"x",
",",
"y",
"=",
"round",
"(",
"coords",
"[",
"0",
"]",
")",
",",
"round",
"(",
"coords",
"[",
"1",
"]",
")",
"self",
".",
"view_rect",
".",
"center",
"=",
"x",
",",
"y",
"mw",
",",
... | center the map on a pixel
float numbers will be rounded.
:param coords: (number, number) | [
"center",
"the",
"map",
"on",
"a",
"pixel"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L95-L163 | train | 23,107 |
bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer.draw | def draw(self, surface, rect, surfaces=None):
""" Draw the map onto a surface
pass a rect that defines the draw area for:
drawing to an area smaller that the whole window/screen
surfaces may optionally be passed that will be blitted onto the surface.
this must be a sequence of tuples containing a layer number, image, and
rect in screen coordinates. surfaces will be drawn in order passed,
and will be correctly drawn with tiles from a higher layer overlapping
the surface.
surfaces list should be in the following format:
[ (layer, surface, rect), ... ]
or this:
[ (layer, surface, rect, blendmode_flags), ... ]
:param surface: pygame surface to draw to
:param rect: area to draw to
:param surfaces: optional sequence of surfaces to interlace between tiles
:return rect: area that was drawn over
"""
if self._zoom_level == 1.0:
self._render_map(surface, rect, surfaces)
else:
self._render_map(self._zoom_buffer, self._zoom_buffer.get_rect(), surfaces)
self.scaling_function(self._zoom_buffer, rect.size, surface)
return self._previous_blit.copy() | python | def draw(self, surface, rect, surfaces=None):
""" Draw the map onto a surface
pass a rect that defines the draw area for:
drawing to an area smaller that the whole window/screen
surfaces may optionally be passed that will be blitted onto the surface.
this must be a sequence of tuples containing a layer number, image, and
rect in screen coordinates. surfaces will be drawn in order passed,
and will be correctly drawn with tiles from a higher layer overlapping
the surface.
surfaces list should be in the following format:
[ (layer, surface, rect), ... ]
or this:
[ (layer, surface, rect, blendmode_flags), ... ]
:param surface: pygame surface to draw to
:param rect: area to draw to
:param surfaces: optional sequence of surfaces to interlace between tiles
:return rect: area that was drawn over
"""
if self._zoom_level == 1.0:
self._render_map(surface, rect, surfaces)
else:
self._render_map(self._zoom_buffer, self._zoom_buffer.get_rect(), surfaces)
self.scaling_function(self._zoom_buffer, rect.size, surface)
return self._previous_blit.copy() | [
"def",
"draw",
"(",
"self",
",",
"surface",
",",
"rect",
",",
"surfaces",
"=",
"None",
")",
":",
"if",
"self",
".",
"_zoom_level",
"==",
"1.0",
":",
"self",
".",
"_render_map",
"(",
"surface",
",",
"rect",
",",
"surfaces",
")",
"else",
":",
"self",
... | Draw the map onto a surface
pass a rect that defines the draw area for:
drawing to an area smaller that the whole window/screen
surfaces may optionally be passed that will be blitted onto the surface.
this must be a sequence of tuples containing a layer number, image, and
rect in screen coordinates. surfaces will be drawn in order passed,
and will be correctly drawn with tiles from a higher layer overlapping
the surface.
surfaces list should be in the following format:
[ (layer, surface, rect), ... ]
or this:
[ (layer, surface, rect, blendmode_flags), ... ]
:param surface: pygame surface to draw to
:param rect: area to draw to
:param surfaces: optional sequence of surfaces to interlace between tiles
:return rect: area that was drawn over | [
"Draw",
"the",
"map",
"onto",
"a",
"surface"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L165-L193 | train | 23,108 |
bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer.set_size | def set_size(self, size):
""" Set the size of the map in pixels
This is an expensive operation, do only when absolutely needed.
:param size: (width, height) pixel size of camera/view of the group
"""
buffer_size = self._calculate_zoom_buffer_size(size, self._zoom_level)
self._size = size
self._initialize_buffers(buffer_size) | python | def set_size(self, size):
""" Set the size of the map in pixels
This is an expensive operation, do only when absolutely needed.
:param size: (width, height) pixel size of camera/view of the group
"""
buffer_size = self._calculate_zoom_buffer_size(size, self._zoom_level)
self._size = size
self._initialize_buffers(buffer_size) | [
"def",
"set_size",
"(",
"self",
",",
"size",
")",
":",
"buffer_size",
"=",
"self",
".",
"_calculate_zoom_buffer_size",
"(",
"size",
",",
"self",
".",
"_zoom_level",
")",
"self",
".",
"_size",
"=",
"size",
"self",
".",
"_initialize_buffers",
"(",
"buffer_size... | Set the size of the map in pixels
This is an expensive operation, do only when absolutely needed.
:param size: (width, height) pixel size of camera/view of the group | [
"Set",
"the",
"size",
"of",
"the",
"map",
"in",
"pixels"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L219-L228 | train | 23,109 |
bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer.translate_point | def translate_point(self, point):
""" Translate world coordinates and return screen coordinates. Respects zoom level
Will be returned as tuple.
:rtype: tuple
"""
mx, my = self.get_center_offset()
if self._zoom_level == 1.0:
return point[0] + mx, point[1] + my
else:
return int(round((point[0] + mx)) * self._real_ratio_x), int(round((point[1] + my) * self._real_ratio_y)) | python | def translate_point(self, point):
""" Translate world coordinates and return screen coordinates. Respects zoom level
Will be returned as tuple.
:rtype: tuple
"""
mx, my = self.get_center_offset()
if self._zoom_level == 1.0:
return point[0] + mx, point[1] + my
else:
return int(round((point[0] + mx)) * self._real_ratio_x), int(round((point[1] + my) * self._real_ratio_y)) | [
"def",
"translate_point",
"(",
"self",
",",
"point",
")",
":",
"mx",
",",
"my",
"=",
"self",
".",
"get_center_offset",
"(",
")",
"if",
"self",
".",
"_zoom_level",
"==",
"1.0",
":",
"return",
"point",
"[",
"0",
"]",
"+",
"mx",
",",
"point",
"[",
"1"... | Translate world coordinates and return screen coordinates. Respects zoom level
Will be returned as tuple.
:rtype: tuple | [
"Translate",
"world",
"coordinates",
"and",
"return",
"screen",
"coordinates",
".",
"Respects",
"zoom",
"level"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L246-L257 | train | 23,110 |
bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer.translate_points | def translate_points(self, points):
""" Translate coordinates and return screen coordinates
Will be returned in order passed as tuples.
:return: list
"""
retval = list()
append = retval.append
sx, sy = self.get_center_offset()
if self._zoom_level == 1.0:
for c in points:
append((c[0] + sx, c[1] + sy))
else:
rx = self._real_ratio_x
ry = self._real_ratio_y
for c in points:
append((int(round((c[0] + sx) * rx)), int(round((c[1] + sy) * ry))))
return retval | python | def translate_points(self, points):
""" Translate coordinates and return screen coordinates
Will be returned in order passed as tuples.
:return: list
"""
retval = list()
append = retval.append
sx, sy = self.get_center_offset()
if self._zoom_level == 1.0:
for c in points:
append((c[0] + sx, c[1] + sy))
else:
rx = self._real_ratio_x
ry = self._real_ratio_y
for c in points:
append((int(round((c[0] + sx) * rx)), int(round((c[1] + sy) * ry))))
return retval | [
"def",
"translate_points",
"(",
"self",
",",
"points",
")",
":",
"retval",
"=",
"list",
"(",
")",
"append",
"=",
"retval",
".",
"append",
"sx",
",",
"sy",
"=",
"self",
".",
"get_center_offset",
"(",
")",
"if",
"self",
".",
"_zoom_level",
"==",
"1.0",
... | Translate coordinates and return screen coordinates
Will be returned in order passed as tuples.
:return: list | [
"Translate",
"coordinates",
"and",
"return",
"screen",
"coordinates"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L273-L291 | train | 23,111 |
bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer._render_map | def _render_map(self, surface, rect, surfaces):
""" Render the map and optional surfaces to destination surface
:param surface: pygame surface to draw to
:param rect: area to draw to
:param surfaces: optional sequence of surfaces to interlace between tiles
"""
self._tile_queue = self.data.process_animation_queue(self._tile_view)
self._tile_queue and self._flush_tile_queue(self._buffer)
# TODO: could maybe optimize to remove just the edges, ideally by drawing lines
# if not self.anchored_view:
# surface.fill(self._clear_color, self._previous_blit)
if not self._anchored_view:
self._clear_surface(surface, self._previous_blit)
offset = -self._x_offset + rect.left, -self._y_offset + rect.top
with surface_clipping_context(surface, rect):
self._previous_blit = surface.blit(self._buffer, offset)
if surfaces:
surfaces_offset = -offset[0], -offset[1]
self._draw_surfaces(surface, surfaces_offset, surfaces) | python | def _render_map(self, surface, rect, surfaces):
""" Render the map and optional surfaces to destination surface
:param surface: pygame surface to draw to
:param rect: area to draw to
:param surfaces: optional sequence of surfaces to interlace between tiles
"""
self._tile_queue = self.data.process_animation_queue(self._tile_view)
self._tile_queue and self._flush_tile_queue(self._buffer)
# TODO: could maybe optimize to remove just the edges, ideally by drawing lines
# if not self.anchored_view:
# surface.fill(self._clear_color, self._previous_blit)
if not self._anchored_view:
self._clear_surface(surface, self._previous_blit)
offset = -self._x_offset + rect.left, -self._y_offset + rect.top
with surface_clipping_context(surface, rect):
self._previous_blit = surface.blit(self._buffer, offset)
if surfaces:
surfaces_offset = -offset[0], -offset[1]
self._draw_surfaces(surface, surfaces_offset, surfaces) | [
"def",
"_render_map",
"(",
"self",
",",
"surface",
",",
"rect",
",",
"surfaces",
")",
":",
"self",
".",
"_tile_queue",
"=",
"self",
".",
"data",
".",
"process_animation_queue",
"(",
"self",
".",
"_tile_view",
")",
"self",
".",
"_tile_queue",
"and",
"self",... | Render the map and optional surfaces to destination surface
:param surface: pygame surface to draw to
:param rect: area to draw to
:param surfaces: optional sequence of surfaces to interlace between tiles | [
"Render",
"the",
"map",
"and",
"optional",
"surfaces",
"to",
"destination",
"surface"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L315-L337 | train | 23,112 |
bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer._clear_surface | def _clear_surface(self, surface, rect=None):
""" Clear the buffer, taking in account colorkey or alpha
:return:
"""
clear_color = self._rgb_clear_color if self._clear_color is None else self._clear_color
surface.fill(clear_color, rect) | python | def _clear_surface(self, surface, rect=None):
""" Clear the buffer, taking in account colorkey or alpha
:return:
"""
clear_color = self._rgb_clear_color if self._clear_color is None else self._clear_color
surface.fill(clear_color, rect) | [
"def",
"_clear_surface",
"(",
"self",
",",
"surface",
",",
"rect",
"=",
"None",
")",
":",
"clear_color",
"=",
"self",
".",
"_rgb_clear_color",
"if",
"self",
".",
"_clear_color",
"is",
"None",
"else",
"self",
".",
"_clear_color",
"surface",
".",
"fill",
"("... | Clear the buffer, taking in account colorkey or alpha
:return: | [
"Clear",
"the",
"buffer",
"taking",
"in",
"account",
"colorkey",
"or",
"alpha"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L339-L345 | train | 23,113 |
bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer._draw_surfaces | def _draw_surfaces(self, surface, offset, surfaces):
""" Draw surfaces onto buffer, then redraw tiles that cover them
:param surface: destination
:param offset: offset to compensate for buffer alignment
:param surfaces: sequence of surfaces to blit
"""
surface_blit = surface.blit
ox, oy = offset
left, top = self._tile_view.topleft
hit = self._layer_quadtree.hit
get_tile = self.data.get_tile_image
tile_layers = tuple(self.data.visible_tile_layers)
dirty = list()
dirty_append = dirty.append
# TODO: check to avoid sorting overhead
# sort layers, then the y value
def sprite_sort(i):
return i[2], i[1][1] + i[0].get_height()
surfaces.sort(key=sprite_sort)
layer_getter = itemgetter(2)
for layer, group in groupby(surfaces, layer_getter):
del dirty[:]
for i in group:
try:
flags = i[3]
except IndexError:
dirty_append(surface_blit(i[0], i[1]))
else:
dirty_append(surface_blit(i[0], i[1], None, flags))
# TODO: make set of covered tiles, in the case where a cluster
# of sprite surfaces causes excessive over tile overdrawing
for dirty_rect in dirty:
for r in hit(dirty_rect.move(ox, oy)):
x, y, tw, th = r
for l in [i for i in tile_layers if gt(i, layer)]:
if self.tall_sprites and l == layer + 1:
if y - oy + th <= dirty_rect.bottom - self.tall_sprites:
continue
tile = get_tile(x // tw + left, y // th + top, l)
tile and surface_blit(tile, (x - ox, y - oy)) | python | def _draw_surfaces(self, surface, offset, surfaces):
""" Draw surfaces onto buffer, then redraw tiles that cover them
:param surface: destination
:param offset: offset to compensate for buffer alignment
:param surfaces: sequence of surfaces to blit
"""
surface_blit = surface.blit
ox, oy = offset
left, top = self._tile_view.topleft
hit = self._layer_quadtree.hit
get_tile = self.data.get_tile_image
tile_layers = tuple(self.data.visible_tile_layers)
dirty = list()
dirty_append = dirty.append
# TODO: check to avoid sorting overhead
# sort layers, then the y value
def sprite_sort(i):
return i[2], i[1][1] + i[0].get_height()
surfaces.sort(key=sprite_sort)
layer_getter = itemgetter(2)
for layer, group in groupby(surfaces, layer_getter):
del dirty[:]
for i in group:
try:
flags = i[3]
except IndexError:
dirty_append(surface_blit(i[0], i[1]))
else:
dirty_append(surface_blit(i[0], i[1], None, flags))
# TODO: make set of covered tiles, in the case where a cluster
# of sprite surfaces causes excessive over tile overdrawing
for dirty_rect in dirty:
for r in hit(dirty_rect.move(ox, oy)):
x, y, tw, th = r
for l in [i for i in tile_layers if gt(i, layer)]:
if self.tall_sprites and l == layer + 1:
if y - oy + th <= dirty_rect.bottom - self.tall_sprites:
continue
tile = get_tile(x // tw + left, y // th + top, l)
tile and surface_blit(tile, (x - ox, y - oy)) | [
"def",
"_draw_surfaces",
"(",
"self",
",",
"surface",
",",
"offset",
",",
"surfaces",
")",
":",
"surface_blit",
"=",
"surface",
".",
"blit",
"ox",
",",
"oy",
"=",
"offset",
"left",
",",
"top",
"=",
"self",
".",
"_tile_view",
".",
"topleft",
"hit",
"=",... | Draw surfaces onto buffer, then redraw tiles that cover them
:param surface: destination
:param offset: offset to compensate for buffer alignment
:param surfaces: sequence of surfaces to blit | [
"Draw",
"surfaces",
"onto",
"buffer",
"then",
"redraw",
"tiles",
"that",
"cover",
"them"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L347-L394 | train | 23,114 |
bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer._queue_edge_tiles | def _queue_edge_tiles(self, dx, dy):
""" Queue edge tiles and clear edge areas on buffer if needed
:param dx: Edge along X axis to enqueue
:param dy: Edge along Y axis to enqueue
:return: None
"""
v = self._tile_view
tw, th = self.data.tile_size
self._tile_queue = iter([])
def append(rect):
self._tile_queue = chain(self._tile_queue, self.data.get_tile_images_by_rect(rect))
# TODO: optimize so fill is only used when map is smaller than buffer
self._clear_surface(self._buffer, ((rect[0] - v.left) * tw, (rect[1] - v.top) * th,
rect[2] * tw, rect[3] * th))
if dx > 0: # right side
append((v.right - 1, v.top, dx, v.height))
elif dx < 0: # left side
append((v.left, v.top, -dx, v.height))
if dy > 0: # bottom side
append((v.left, v.bottom - 1, v.width, dy))
elif dy < 0: # top side
append((v.left, v.top, v.width, -dy)) | python | def _queue_edge_tiles(self, dx, dy):
""" Queue edge tiles and clear edge areas on buffer if needed
:param dx: Edge along X axis to enqueue
:param dy: Edge along Y axis to enqueue
:return: None
"""
v = self._tile_view
tw, th = self.data.tile_size
self._tile_queue = iter([])
def append(rect):
self._tile_queue = chain(self._tile_queue, self.data.get_tile_images_by_rect(rect))
# TODO: optimize so fill is only used when map is smaller than buffer
self._clear_surface(self._buffer, ((rect[0] - v.left) * tw, (rect[1] - v.top) * th,
rect[2] * tw, rect[3] * th))
if dx > 0: # right side
append((v.right - 1, v.top, dx, v.height))
elif dx < 0: # left side
append((v.left, v.top, -dx, v.height))
if dy > 0: # bottom side
append((v.left, v.bottom - 1, v.width, dy))
elif dy < 0: # top side
append((v.left, v.top, v.width, -dy)) | [
"def",
"_queue_edge_tiles",
"(",
"self",
",",
"dx",
",",
"dy",
")",
":",
"v",
"=",
"self",
".",
"_tile_view",
"tw",
",",
"th",
"=",
"self",
".",
"data",
".",
"tile_size",
"self",
".",
"_tile_queue",
"=",
"iter",
"(",
"[",
"]",
")",
"def",
"append",... | Queue edge tiles and clear edge areas on buffer if needed
:param dx: Edge along X axis to enqueue
:param dy: Edge along Y axis to enqueue
:return: None | [
"Queue",
"edge",
"tiles",
"and",
"clear",
"edge",
"areas",
"on",
"buffer",
"if",
"needed"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L396-L423 | train | 23,115 |
bitcraft/pyscroll | pyscroll/orthographic.py | BufferedRenderer._create_buffers | def _create_buffers(self, view_size, buffer_size):
""" Create the buffers, taking in account pixel alpha or colorkey
:param view_size: pixel size of the view
:param buffer_size: pixel size of the buffer
"""
requires_zoom_buffer = not view_size == buffer_size
self._zoom_buffer = None
if self._clear_color is None:
if requires_zoom_buffer:
self._zoom_buffer = Surface(view_size)
self._buffer = Surface(buffer_size)
elif self._clear_color == self._rgba_clear_color:
if requires_zoom_buffer:
self._zoom_buffer = Surface(view_size, flags=pygame.SRCALPHA)
self._buffer = Surface(buffer_size, flags=pygame.SRCALPHA)
self.data.convert_surfaces(self._buffer, True)
elif self._clear_color is not self._rgb_clear_color:
if requires_zoom_buffer:
self._zoom_buffer = Surface(view_size, flags=pygame.RLEACCEL)
self._zoom_buffer.set_colorkey(self._clear_color)
self._buffer = Surface(buffer_size, flags=pygame.RLEACCEL)
self._buffer.set_colorkey(self._clear_color)
self._buffer.fill(self._clear_color) | python | def _create_buffers(self, view_size, buffer_size):
""" Create the buffers, taking in account pixel alpha or colorkey
:param view_size: pixel size of the view
:param buffer_size: pixel size of the buffer
"""
requires_zoom_buffer = not view_size == buffer_size
self._zoom_buffer = None
if self._clear_color is None:
if requires_zoom_buffer:
self._zoom_buffer = Surface(view_size)
self._buffer = Surface(buffer_size)
elif self._clear_color == self._rgba_clear_color:
if requires_zoom_buffer:
self._zoom_buffer = Surface(view_size, flags=pygame.SRCALPHA)
self._buffer = Surface(buffer_size, flags=pygame.SRCALPHA)
self.data.convert_surfaces(self._buffer, True)
elif self._clear_color is not self._rgb_clear_color:
if requires_zoom_buffer:
self._zoom_buffer = Surface(view_size, flags=pygame.RLEACCEL)
self._zoom_buffer.set_colorkey(self._clear_color)
self._buffer = Surface(buffer_size, flags=pygame.RLEACCEL)
self._buffer.set_colorkey(self._clear_color)
self._buffer.fill(self._clear_color) | [
"def",
"_create_buffers",
"(",
"self",
",",
"view_size",
",",
"buffer_size",
")",
":",
"requires_zoom_buffer",
"=",
"not",
"view_size",
"==",
"buffer_size",
"self",
".",
"_zoom_buffer",
"=",
"None",
"if",
"self",
".",
"_clear_color",
"is",
"None",
":",
"if",
... | Create the buffers, taking in account pixel alpha or colorkey
:param view_size: pixel size of the view
:param buffer_size: pixel size of the buffer | [
"Create",
"the",
"buffers",
"taking",
"in",
"account",
"pixel",
"alpha",
"or",
"colorkey"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/orthographic.py#L433-L457 | train | 23,116 |
bitcraft/pyscroll | pyscroll/data.py | PyscrollDataAdapter.reload_animations | def reload_animations(self):
""" Reload animation information
PyscrollDataAdapter.get_animations must be implemented
"""
self._update_time()
self._animation_queue = list()
self._tracked_gids = set()
self._animation_map = dict()
for gid, frame_data in self.get_animations():
self._tracked_gids.add(gid)
frames = list()
for frame_gid, frame_duration in frame_data:
image = self._get_tile_image_by_id(frame_gid)
frames.append(AnimationFrame(image, frame_duration))
# the following line is slow when loading maps, but avoids overhead when rendering
# positions = set(self.tmx.get_tile_locations_by_gid(gid))
# ideally, positions would be populated with all the known
# locations of an animation, but searching for their locations
# is slow. so it will be updated as the map is drawn.
positions = set()
ani = AnimationToken(positions, frames, self._last_time)
self._animation_map[gid] = ani
heappush(self._animation_queue, ani) | python | def reload_animations(self):
""" Reload animation information
PyscrollDataAdapter.get_animations must be implemented
"""
self._update_time()
self._animation_queue = list()
self._tracked_gids = set()
self._animation_map = dict()
for gid, frame_data in self.get_animations():
self._tracked_gids.add(gid)
frames = list()
for frame_gid, frame_duration in frame_data:
image = self._get_tile_image_by_id(frame_gid)
frames.append(AnimationFrame(image, frame_duration))
# the following line is slow when loading maps, but avoids overhead when rendering
# positions = set(self.tmx.get_tile_locations_by_gid(gid))
# ideally, positions would be populated with all the known
# locations of an animation, but searching for their locations
# is slow. so it will be updated as the map is drawn.
positions = set()
ani = AnimationToken(positions, frames, self._last_time)
self._animation_map[gid] = ani
heappush(self._animation_queue, ani) | [
"def",
"reload_animations",
"(",
"self",
")",
":",
"self",
".",
"_update_time",
"(",
")",
"self",
".",
"_animation_queue",
"=",
"list",
"(",
")",
"self",
".",
"_tracked_gids",
"=",
"set",
"(",
")",
"self",
".",
"_animation_map",
"=",
"dict",
"(",
")",
... | Reload animation information
PyscrollDataAdapter.get_animations must be implemented | [
"Reload",
"animation",
"information"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L132-L161 | train | 23,117 |
bitcraft/pyscroll | pyscroll/data.py | PyscrollDataAdapter.get_tile_image | def get_tile_image(self, x, y, l):
""" Get a tile image, respecting current animations
:param x: x coordinate
:param y: y coordinate
:param l: layer
:type x: int
:type y: int
:type l: int
:rtype: pygame.Surface
"""
# disabled for now, re-enable when support for generic maps is restored
# # since the tile has been queried, assume it wants to be checked
# # for animations sometime in the future
# if self._animation_queue:
# self._tracked_tiles.add((x, y, l))
try:
# animated, so return the correct frame
return self._animated_tile[(x, y, l)]
except KeyError:
# not animated, so return surface from data, if any
return self._get_tile_image(x, y, l) | python | def get_tile_image(self, x, y, l):
""" Get a tile image, respecting current animations
:param x: x coordinate
:param y: y coordinate
:param l: layer
:type x: int
:type y: int
:type l: int
:rtype: pygame.Surface
"""
# disabled for now, re-enable when support for generic maps is restored
# # since the tile has been queried, assume it wants to be checked
# # for animations sometime in the future
# if self._animation_queue:
# self._tracked_tiles.add((x, y, l))
try:
# animated, so return the correct frame
return self._animated_tile[(x, y, l)]
except KeyError:
# not animated, so return surface from data, if any
return self._get_tile_image(x, y, l) | [
"def",
"get_tile_image",
"(",
"self",
",",
"x",
",",
"y",
",",
"l",
")",
":",
"# disabled for now, re-enable when support for generic maps is restored",
"# # since the tile has been queried, assume it wants to be checked",
"# # for animations sometime in the future",
"# if self._animat... | Get a tile image, respecting current animations
:param x: x coordinate
:param y: y coordinate
:param l: layer
:type x: int
:type y: int
:type l: int
:rtype: pygame.Surface | [
"Get",
"a",
"tile",
"image",
"respecting",
"current",
"animations"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L163-L189 | train | 23,118 |
bitcraft/pyscroll | pyscroll/data.py | PyscrollDataAdapter.get_tile_images_by_rect | def get_tile_images_by_rect(self, rect):
""" Given a 2d area, return generator of tile images inside
Given the coordinates, yield the following tuple for each tile:
X, Y, Layer Number, pygame Surface
This method also defines render order by re arranging the
positions of each tile as it is yielded to the renderer.
There is an optimization that you can make for your data:
If you can provide access to tile information in a batch,
then pyscroll can access data faster and render quicker.
To implement this optimization, override this method.
Not like python 'Range': should include the end index!
:param rect: a rect-like object that defines tiles to draw
:return: generator
"""
x1, y1, x2, y2 = rect_to_bb(rect)
for layer in self.visible_tile_layers:
for y, x in product(range(y1, y2 + 1),
range(x1, x2 + 1)):
tile = self.get_tile_image(x, y, layer)
if tile:
yield x, y, layer, tile | python | def get_tile_images_by_rect(self, rect):
""" Given a 2d area, return generator of tile images inside
Given the coordinates, yield the following tuple for each tile:
X, Y, Layer Number, pygame Surface
This method also defines render order by re arranging the
positions of each tile as it is yielded to the renderer.
There is an optimization that you can make for your data:
If you can provide access to tile information in a batch,
then pyscroll can access data faster and render quicker.
To implement this optimization, override this method.
Not like python 'Range': should include the end index!
:param rect: a rect-like object that defines tiles to draw
:return: generator
"""
x1, y1, x2, y2 = rect_to_bb(rect)
for layer in self.visible_tile_layers:
for y, x in product(range(y1, y2 + 1),
range(x1, x2 + 1)):
tile = self.get_tile_image(x, y, layer)
if tile:
yield x, y, layer, tile | [
"def",
"get_tile_images_by_rect",
"(",
"self",
",",
"rect",
")",
":",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"=",
"rect_to_bb",
"(",
"rect",
")",
"for",
"layer",
"in",
"self",
".",
"visible_tile_layers",
":",
"for",
"y",
",",
"x",
"in",
"product",
"(... | Given a 2d area, return generator of tile images inside
Given the coordinates, yield the following tuple for each tile:
X, Y, Layer Number, pygame Surface
This method also defines render order by re arranging the
positions of each tile as it is yielded to the renderer.
There is an optimization that you can make for your data:
If you can provide access to tile information in a batch,
then pyscroll can access data faster and render quicker.
To implement this optimization, override this method.
Not like python 'Range': should include the end index!
:param rect: a rect-like object that defines tiles to draw
:return: generator | [
"Given",
"a",
"2d",
"area",
"return",
"generator",
"of",
"tile",
"images",
"inside"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L251-L277 | train | 23,119 |
bitcraft/pyscroll | pyscroll/data.py | TiledMapData.convert_surfaces | def convert_surfaces(self, parent, alpha=False):
""" Convert all images in the data to match the parent
:param parent: pygame.Surface
:param alpha: preserve alpha channel or not
:return: None
"""
images = list()
for i in self.tmx.images:
try:
if alpha:
images.append(i.convert_alpha(parent))
else:
images.append(i.convert(parent))
except AttributeError:
images.append(None)
self.tmx.images = images | python | def convert_surfaces(self, parent, alpha=False):
""" Convert all images in the data to match the parent
:param parent: pygame.Surface
:param alpha: preserve alpha channel or not
:return: None
"""
images = list()
for i in self.tmx.images:
try:
if alpha:
images.append(i.convert_alpha(parent))
else:
images.append(i.convert(parent))
except AttributeError:
images.append(None)
self.tmx.images = images | [
"def",
"convert_surfaces",
"(",
"self",
",",
"parent",
",",
"alpha",
"=",
"False",
")",
":",
"images",
"=",
"list",
"(",
")",
"for",
"i",
"in",
"self",
".",
"tmx",
".",
"images",
":",
"try",
":",
"if",
"alpha",
":",
"images",
".",
"append",
"(",
... | Convert all images in the data to match the parent
:param parent: pygame.Surface
:param alpha: preserve alpha channel or not
:return: None | [
"Convert",
"all",
"images",
"in",
"the",
"data",
"to",
"match",
"the",
"parent"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L301-L317 | train | 23,120 |
bitcraft/pyscroll | pyscroll/data.py | TiledMapData.visible_object_layers | def visible_object_layers(self):
""" This must return layer objects
This is not required for custom data formats.
:return: Sequence of pytmx object layers/groups
"""
return (layer for layer in self.tmx.visible_layers
if isinstance(layer, pytmx.TiledObjectGroup)) | python | def visible_object_layers(self):
""" This must return layer objects
This is not required for custom data formats.
:return: Sequence of pytmx object layers/groups
"""
return (layer for layer in self.tmx.visible_layers
if isinstance(layer, pytmx.TiledObjectGroup)) | [
"def",
"visible_object_layers",
"(",
"self",
")",
":",
"return",
"(",
"layer",
"for",
"layer",
"in",
"self",
".",
"tmx",
".",
"visible_layers",
"if",
"isinstance",
"(",
"layer",
",",
"pytmx",
".",
"TiledObjectGroup",
")",
")"
] | This must return layer objects
This is not required for custom data formats.
:return: Sequence of pytmx object layers/groups | [
"This",
"must",
"return",
"layer",
"objects"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L344-L352 | train | 23,121 |
bitcraft/pyscroll | pyscroll/data.py | TiledMapData.get_tile_images_by_rect | def get_tile_images_by_rect(self, rect):
""" Speed up data access
More efficient because data is accessed and cached locally
"""
def rev(seq, start, stop):
if start < 0:
start = 0
return enumerate(seq[start:stop + 1], start)
x1, y1, x2, y2 = rect_to_bb(rect)
images = self.tmx.images
layers = self.tmx.layers
at = self._animated_tile
tracked_gids = self._tracked_gids
anim_map = self._animation_map
track = bool(self._animation_queue)
for l in self.tmx.visible_tile_layers:
for y, row in rev(layers[l].data, y1, y2):
for x, gid in [i for i in rev(row, x1, x2) if i[1]]:
# since the tile has been queried, assume it wants to be checked
# for animations sometime in the future
if track and gid in tracked_gids:
anim_map[gid].positions.add((x, y, l))
try:
# animated, so return the correct frame
yield x, y, l, at[(x, y, l)]
except KeyError:
# not animated, so return surface from data, if any
yield x, y, l, images[gid] | python | def get_tile_images_by_rect(self, rect):
""" Speed up data access
More efficient because data is accessed and cached locally
"""
def rev(seq, start, stop):
if start < 0:
start = 0
return enumerate(seq[start:stop + 1], start)
x1, y1, x2, y2 = rect_to_bb(rect)
images = self.tmx.images
layers = self.tmx.layers
at = self._animated_tile
tracked_gids = self._tracked_gids
anim_map = self._animation_map
track = bool(self._animation_queue)
for l in self.tmx.visible_tile_layers:
for y, row in rev(layers[l].data, y1, y2):
for x, gid in [i for i in rev(row, x1, x2) if i[1]]:
# since the tile has been queried, assume it wants to be checked
# for animations sometime in the future
if track and gid in tracked_gids:
anim_map[gid].positions.add((x, y, l))
try:
# animated, so return the correct frame
yield x, y, l, at[(x, y, l)]
except KeyError:
# not animated, so return surface from data, if any
yield x, y, l, images[gid] | [
"def",
"get_tile_images_by_rect",
"(",
"self",
",",
"rect",
")",
":",
"def",
"rev",
"(",
"seq",
",",
"start",
",",
"stop",
")",
":",
"if",
"start",
"<",
"0",
":",
"start",
"=",
"0",
"return",
"enumerate",
"(",
"seq",
"[",
"start",
":",
"stop",
"+",... | Speed up data access
More efficient because data is accessed and cached locally | [
"Speed",
"up",
"data",
"access"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L370-L404 | train | 23,122 |
bitcraft/pyscroll | tutorial/quest.py | Hero.move_back | def move_back(self, dt):
""" If called after an update, the sprite can move back
"""
self._position = self._old_position
self.rect.topleft = self._position
self.feet.midbottom = self.rect.midbottom | python | def move_back(self, dt):
""" If called after an update, the sprite can move back
"""
self._position = self._old_position
self.rect.topleft = self._position
self.feet.midbottom = self.rect.midbottom | [
"def",
"move_back",
"(",
"self",
",",
"dt",
")",
":",
"self",
".",
"_position",
"=",
"self",
".",
"_old_position",
"self",
".",
"rect",
".",
"topleft",
"=",
"self",
".",
"_position",
"self",
".",
"feet",
".",
"midbottom",
"=",
"self",
".",
"rect",
".... | If called after an update, the sprite can move back | [
"If",
"called",
"after",
"an",
"update",
"the",
"sprite",
"can",
"move",
"back"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/tutorial/quest.py#L86-L91 | train | 23,123 |
bitcraft/pyscroll | tutorial/quest.py | QuestGame.handle_input | def handle_input(self):
""" Handle pygame input events
"""
poll = pygame.event.poll
event = poll()
while event:
if event.type == QUIT:
self.running = False
break
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.running = False
break
elif event.key == K_EQUALS:
self.map_layer.zoom += .25
elif event.key == K_MINUS:
value = self.map_layer.zoom - .25
if value > 0:
self.map_layer.zoom = value
# this will be handled if the window is resized
elif event.type == VIDEORESIZE:
init_screen(event.w, event.h)
self.map_layer.set_size((event.w, event.h))
event = poll()
# using get_pressed is slightly less accurate than testing for events
# but is much easier to use.
pressed = pygame.key.get_pressed()
if pressed[K_UP]:
self.hero.velocity[1] = -HERO_MOVE_SPEED
elif pressed[K_DOWN]:
self.hero.velocity[1] = HERO_MOVE_SPEED
else:
self.hero.velocity[1] = 0
if pressed[K_LEFT]:
self.hero.velocity[0] = -HERO_MOVE_SPEED
elif pressed[K_RIGHT]:
self.hero.velocity[0] = HERO_MOVE_SPEED
else:
self.hero.velocity[0] = 0 | python | def handle_input(self):
""" Handle pygame input events
"""
poll = pygame.event.poll
event = poll()
while event:
if event.type == QUIT:
self.running = False
break
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.running = False
break
elif event.key == K_EQUALS:
self.map_layer.zoom += .25
elif event.key == K_MINUS:
value = self.map_layer.zoom - .25
if value > 0:
self.map_layer.zoom = value
# this will be handled if the window is resized
elif event.type == VIDEORESIZE:
init_screen(event.w, event.h)
self.map_layer.set_size((event.w, event.h))
event = poll()
# using get_pressed is slightly less accurate than testing for events
# but is much easier to use.
pressed = pygame.key.get_pressed()
if pressed[K_UP]:
self.hero.velocity[1] = -HERO_MOVE_SPEED
elif pressed[K_DOWN]:
self.hero.velocity[1] = HERO_MOVE_SPEED
else:
self.hero.velocity[1] = 0
if pressed[K_LEFT]:
self.hero.velocity[0] = -HERO_MOVE_SPEED
elif pressed[K_RIGHT]:
self.hero.velocity[0] = HERO_MOVE_SPEED
else:
self.hero.velocity[0] = 0 | [
"def",
"handle_input",
"(",
"self",
")",
":",
"poll",
"=",
"pygame",
".",
"event",
".",
"poll",
"event",
"=",
"poll",
"(",
")",
"while",
"event",
":",
"if",
"event",
".",
"type",
"==",
"QUIT",
":",
"self",
".",
"running",
"=",
"False",
"break",
"el... | Handle pygame input events | [
"Handle",
"pygame",
"input",
"events"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/tutorial/quest.py#L149-L195 | train | 23,124 |
bitcraft/pyscroll | tutorial/quest.py | QuestGame.update | def update(self, dt):
""" Tasks that occur over time should be handled here
"""
self.group.update(dt)
# check if the sprite's feet are colliding with wall
# sprite must have a rect called feet, and move_back method,
# otherwise this will fail
for sprite in self.group.sprites():
if sprite.feet.collidelist(self.walls) > -1:
sprite.move_back(dt) | python | def update(self, dt):
""" Tasks that occur over time should be handled here
"""
self.group.update(dt)
# check if the sprite's feet are colliding with wall
# sprite must have a rect called feet, and move_back method,
# otherwise this will fail
for sprite in self.group.sprites():
if sprite.feet.collidelist(self.walls) > -1:
sprite.move_back(dt) | [
"def",
"update",
"(",
"self",
",",
"dt",
")",
":",
"self",
".",
"group",
".",
"update",
"(",
"dt",
")",
"# check if the sprite's feet are colliding with wall",
"# sprite must have a rect called feet, and move_back method,",
"# otherwise this will fail",
"for",
"sprite",
"in... | Tasks that occur over time should be handled here | [
"Tasks",
"that",
"occur",
"over",
"time",
"should",
"be",
"handled",
"here"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/tutorial/quest.py#L197-L207 | train | 23,125 |
bitcraft/pyscroll | tutorial/quest.py | QuestGame.run | def run(self):
""" Run the game loop
"""
clock = pygame.time.Clock()
self.running = True
from collections import deque
times = deque(maxlen=30)
try:
while self.running:
dt = clock.tick() / 1000.
times.append(clock.get_fps())
# print(sum(times)/len(times))
self.handle_input()
self.update(dt)
self.draw(screen)
pygame.display.flip()
except KeyboardInterrupt:
self.running = False | python | def run(self):
""" Run the game loop
"""
clock = pygame.time.Clock()
self.running = True
from collections import deque
times = deque(maxlen=30)
try:
while self.running:
dt = clock.tick() / 1000.
times.append(clock.get_fps())
# print(sum(times)/len(times))
self.handle_input()
self.update(dt)
self.draw(screen)
pygame.display.flip()
except KeyboardInterrupt:
self.running = False | [
"def",
"run",
"(",
"self",
")",
":",
"clock",
"=",
"pygame",
".",
"time",
".",
"Clock",
"(",
")",
"self",
".",
"running",
"=",
"True",
"from",
"collections",
"import",
"deque",
"times",
"=",
"deque",
"(",
"maxlen",
"=",
"30",
")",
"try",
":",
"whil... | Run the game loop | [
"Run",
"the",
"game",
"loop"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/tutorial/quest.py#L209-L230 | train | 23,126 |
bitcraft/pyscroll | pyscroll/group.py | PyscrollGroup.draw | def draw(self, surface):
""" Draw all sprites and map onto the surface
:param surface: pygame surface to draw to
:type surface: pygame.surface.Surface
"""
ox, oy = self._map_layer.get_center_offset()
new_surfaces = list()
spritedict = self.spritedict
gl = self.get_layer_of_sprite
new_surfaces_append = new_surfaces.append
for spr in self.sprites():
new_rect = spr.rect.move(ox, oy)
try:
new_surfaces_append((spr.image, new_rect, gl(spr), spr.blendmode))
except AttributeError: # generally should only fail when no blendmode available
new_surfaces_append((spr.image, new_rect, gl(spr)))
spritedict[spr] = new_rect
self.lostsprites = []
return self._map_layer.draw(surface, surface.get_rect(), new_surfaces) | python | def draw(self, surface):
""" Draw all sprites and map onto the surface
:param surface: pygame surface to draw to
:type surface: pygame.surface.Surface
"""
ox, oy = self._map_layer.get_center_offset()
new_surfaces = list()
spritedict = self.spritedict
gl = self.get_layer_of_sprite
new_surfaces_append = new_surfaces.append
for spr in self.sprites():
new_rect = spr.rect.move(ox, oy)
try:
new_surfaces_append((spr.image, new_rect, gl(spr), spr.blendmode))
except AttributeError: # generally should only fail when no blendmode available
new_surfaces_append((spr.image, new_rect, gl(spr)))
spritedict[spr] = new_rect
self.lostsprites = []
return self._map_layer.draw(surface, surface.get_rect(), new_surfaces) | [
"def",
"draw",
"(",
"self",
",",
"surface",
")",
":",
"ox",
",",
"oy",
"=",
"self",
".",
"_map_layer",
".",
"get_center_offset",
"(",
")",
"new_surfaces",
"=",
"list",
"(",
")",
"spritedict",
"=",
"self",
".",
"spritedict",
"gl",
"=",
"self",
".",
"g... | Draw all sprites and map onto the surface
:param surface: pygame surface to draw to
:type surface: pygame.surface.Surface | [
"Draw",
"all",
"sprites",
"and",
"map",
"onto",
"the",
"surface"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/group.py#L34-L56 | train | 23,127 |
bitcraft/pyscroll | pyscroll/isometric.py | IsometricBufferedRenderer.center | def center(self, coords):
""" center the map on a "map pixel"
"""
x, y = [round(i, 0) for i in coords]
self.view_rect.center = x, y
tw, th = self.data.tile_size
left, ox = divmod(x, tw)
top, oy = divmod(y, th)
vec = int(ox / 2), int(oy)
iso = vector2_to_iso(vec)
self._x_offset = iso[0]
self._y_offset = iso[1]
print(self._tile_view.size)
print(self._buffer.get_size())
# center the buffer on the screen
self._x_offset += (self._buffer.get_width() - self.view_rect.width) // 2
self._y_offset += (self._buffer.get_height() - self.view_rect.height) // 4
# adjust the view if the view has changed without a redraw
dx = int(left - self._tile_view.left)
dy = int(top - self._tile_view.top)
view_change = max(abs(dx), abs(dy))
# force redraw every time: edge queuing not supported yet
self._redraw_cutoff = 0
if view_change and (view_change <= self._redraw_cutoff):
self._buffer.scroll(-dx * tw, -dy * th)
self._tile_view.move_ip(dx, dy)
self._queue_edge_tiles(dx, dy)
self._flush_tile_queue()
elif view_change > self._redraw_cutoff:
# logger.info('scrolling too quickly. redraw forced')
self._tile_view.move_ip(dx, dy)
self.redraw_tiles() | python | def center(self, coords):
""" center the map on a "map pixel"
"""
x, y = [round(i, 0) for i in coords]
self.view_rect.center = x, y
tw, th = self.data.tile_size
left, ox = divmod(x, tw)
top, oy = divmod(y, th)
vec = int(ox / 2), int(oy)
iso = vector2_to_iso(vec)
self._x_offset = iso[0]
self._y_offset = iso[1]
print(self._tile_view.size)
print(self._buffer.get_size())
# center the buffer on the screen
self._x_offset += (self._buffer.get_width() - self.view_rect.width) // 2
self._y_offset += (self._buffer.get_height() - self.view_rect.height) // 4
# adjust the view if the view has changed without a redraw
dx = int(left - self._tile_view.left)
dy = int(top - self._tile_view.top)
view_change = max(abs(dx), abs(dy))
# force redraw every time: edge queuing not supported yet
self._redraw_cutoff = 0
if view_change and (view_change <= self._redraw_cutoff):
self._buffer.scroll(-dx * tw, -dy * th)
self._tile_view.move_ip(dx, dy)
self._queue_edge_tiles(dx, dy)
self._flush_tile_queue()
elif view_change > self._redraw_cutoff:
# logger.info('scrolling too quickly. redraw forced')
self._tile_view.move_ip(dx, dy)
self.redraw_tiles() | [
"def",
"center",
"(",
"self",
",",
"coords",
")",
":",
"x",
",",
"y",
"=",
"[",
"round",
"(",
"i",
",",
"0",
")",
"for",
"i",
"in",
"coords",
"]",
"self",
".",
"view_rect",
".",
"center",
"=",
"x",
",",
"y",
"tw",
",",
"th",
"=",
"self",
".... | center the map on a "map pixel" | [
"center",
"the",
"map",
"on",
"a",
"map",
"pixel"
] | b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/isometric.py#L86-L127 | train | 23,128 |
acsone/click-odoo | click_odoo/env_options.py | env_options.get_odoo_args | def get_odoo_args(self, ctx):
"""Return a list of Odoo command line arguments from the Click context."""
config = ctx.params.get("config")
addons_path = ctx.params.get("addons_path")
database = ctx.params.get("database")
log_level = ctx.params.get("log_level")
logfile = ctx.params.get("logfile")
odoo_args = []
if config:
odoo_args.extend(["--config", config])
if addons_path:
odoo_args.extend(["--addons-path", addons_path])
if database:
odoo_args.extend(["--database", database])
if log_level:
odoo_args.extend(["--log-level", log_level])
if logfile:
odoo_args.extend(["--logfile", logfile])
return odoo_args | python | def get_odoo_args(self, ctx):
"""Return a list of Odoo command line arguments from the Click context."""
config = ctx.params.get("config")
addons_path = ctx.params.get("addons_path")
database = ctx.params.get("database")
log_level = ctx.params.get("log_level")
logfile = ctx.params.get("logfile")
odoo_args = []
if config:
odoo_args.extend(["--config", config])
if addons_path:
odoo_args.extend(["--addons-path", addons_path])
if database:
odoo_args.extend(["--database", database])
if log_level:
odoo_args.extend(["--log-level", log_level])
if logfile:
odoo_args.extend(["--logfile", logfile])
return odoo_args | [
"def",
"get_odoo_args",
"(",
"self",
",",
"ctx",
")",
":",
"config",
"=",
"ctx",
".",
"params",
".",
"get",
"(",
"\"config\"",
")",
"addons_path",
"=",
"ctx",
".",
"params",
".",
"get",
"(",
"\"addons_path\"",
")",
"database",
"=",
"ctx",
".",
"params"... | Return a list of Odoo command line arguments from the Click context. | [
"Return",
"a",
"list",
"of",
"Odoo",
"command",
"line",
"arguments",
"from",
"the",
"Click",
"context",
"."
] | 7335f722bb6edbaf34cee29e027a49f47e83e052 | https://github.com/acsone/click-odoo/blob/7335f722bb6edbaf34cee29e027a49f47e83e052/click_odoo/env_options.py#L123-L144 | train | 23,129 |
williamgilpin/pypdb | pypdb/pypdb.py | make_query | def make_query(search_term, querytype='AdvancedKeywordQuery'):
''' Repackage strings into a search dictionary
This function takes a list of search terms and specifications
and repackages it as a dictionary object that can be used to conduct a search
Parameters
----------
search_term : str
The specific term to search in the database. For specific query types,
the strings that will yield valid results are limited to:
'HoldingsQuery' : A Ggeneral search of the metadata associated with PDB IDs
'ExpTypeQuery' : Experimental Method such as 'X-RAY', 'SOLID-STATE NMR', etc
'AdvancedKeywordQuery' : Any string that appears in the title or abstract
'StructureIdQuery' : Perform a search for a specific Structure ID
'ModifiedStructuresQuery' : Search for related structures
'AdvancedAuthorQuery' : Search by the names of authors associated with entries
'MotifQuery' : Search for a specific motif
'NoLigandQuery' : Find full list of PDB IDs without free ligrands
querytype : str
The type of query to perform, the easiest is an AdvancedKeywordQuery but more
specific types of searches may also be performed
Returns
-------
scan_params : dict
A dictionary representing the query
Examples
--------
This method usually gets used in tandem with do_search
>>> a = make_query('actin network')
>>> print (a)
{'orgPdbQuery': {'description': 'Text Search for: actin',
'keywords': 'actin',
'queryType': 'AdvancedKeywordQuery'}}
>>> search_dict = make_query('actin network')
>>> found_pdbs = do_search(search_dict)
>>> print(found_pdbs)
['1D7M', '3W3D', '4A7H', '4A7L', '4A7N']
>>> search_dict = make_query('T[AG]AGGY',querytype='MotifQuery')
>>> found_pdbs = do_search(search_dict)
>>> print(found_pdbs)
['3LEZ', '3SGH', '4F47']
'''
assert querytype in {'HoldingsQuery', 'ExpTypeQuery',
'AdvancedKeywordQuery','StructureIdQuery',
'ModifiedStructuresQuery', 'AdvancedAuthorQuery', 'MotifQuery',
'NoLigandQuery', 'PubmedIdQuery'
}, 'Query type %s not supported yet' % querytype
query_params = dict()
query_params['queryType'] = querytype
if querytype=='AdvancedKeywordQuery':
query_params['description'] = 'Text Search for: '+ search_term
query_params['keywords'] = search_term
elif querytype=='NoLigandQuery':
query_params['haveLigands'] = 'yes'
elif querytype=='AdvancedAuthorQuery':
query_params['description'] = 'Author Name: '+ search_term
query_params['searchType'] = 'All Authors'
query_params['audit_author.name'] = search_term
query_params['exactMatch'] = 'false'
elif querytype=='MotifQuery':
query_params['description'] = 'Motif Query For: '+ search_term
query_params['motif'] = search_term
# search for a specific structure
elif querytype in ['StructureIdQuery','ModifiedStructuresQuery']:
query_params['structureIdList'] = search_term
elif querytype=='ExpTypeQuery':
query_params['experimentalMethod'] = search_term
query_params['description'] = 'Experimental Method Search : Experimental Method='+ search_term
query_params['mvStructure.expMethod.value']= search_term
elif querytype=='PubmedIdQuery':
query_params['description'] = 'Pubmed Id Search for Pubmed Id '+ search_term
query_params['pubMedIdList'] = search_term
scan_params = dict()
scan_params['orgPdbQuery'] = query_params
return scan_params | python | def make_query(search_term, querytype='AdvancedKeywordQuery'):
''' Repackage strings into a search dictionary
This function takes a list of search terms and specifications
and repackages it as a dictionary object that can be used to conduct a search
Parameters
----------
search_term : str
The specific term to search in the database. For specific query types,
the strings that will yield valid results are limited to:
'HoldingsQuery' : A Ggeneral search of the metadata associated with PDB IDs
'ExpTypeQuery' : Experimental Method such as 'X-RAY', 'SOLID-STATE NMR', etc
'AdvancedKeywordQuery' : Any string that appears in the title or abstract
'StructureIdQuery' : Perform a search for a specific Structure ID
'ModifiedStructuresQuery' : Search for related structures
'AdvancedAuthorQuery' : Search by the names of authors associated with entries
'MotifQuery' : Search for a specific motif
'NoLigandQuery' : Find full list of PDB IDs without free ligrands
querytype : str
The type of query to perform, the easiest is an AdvancedKeywordQuery but more
specific types of searches may also be performed
Returns
-------
scan_params : dict
A dictionary representing the query
Examples
--------
This method usually gets used in tandem with do_search
>>> a = make_query('actin network')
>>> print (a)
{'orgPdbQuery': {'description': 'Text Search for: actin',
'keywords': 'actin',
'queryType': 'AdvancedKeywordQuery'}}
>>> search_dict = make_query('actin network')
>>> found_pdbs = do_search(search_dict)
>>> print(found_pdbs)
['1D7M', '3W3D', '4A7H', '4A7L', '4A7N']
>>> search_dict = make_query('T[AG]AGGY',querytype='MotifQuery')
>>> found_pdbs = do_search(search_dict)
>>> print(found_pdbs)
['3LEZ', '3SGH', '4F47']
'''
assert querytype in {'HoldingsQuery', 'ExpTypeQuery',
'AdvancedKeywordQuery','StructureIdQuery',
'ModifiedStructuresQuery', 'AdvancedAuthorQuery', 'MotifQuery',
'NoLigandQuery', 'PubmedIdQuery'
}, 'Query type %s not supported yet' % querytype
query_params = dict()
query_params['queryType'] = querytype
if querytype=='AdvancedKeywordQuery':
query_params['description'] = 'Text Search for: '+ search_term
query_params['keywords'] = search_term
elif querytype=='NoLigandQuery':
query_params['haveLigands'] = 'yes'
elif querytype=='AdvancedAuthorQuery':
query_params['description'] = 'Author Name: '+ search_term
query_params['searchType'] = 'All Authors'
query_params['audit_author.name'] = search_term
query_params['exactMatch'] = 'false'
elif querytype=='MotifQuery':
query_params['description'] = 'Motif Query For: '+ search_term
query_params['motif'] = search_term
# search for a specific structure
elif querytype in ['StructureIdQuery','ModifiedStructuresQuery']:
query_params['structureIdList'] = search_term
elif querytype=='ExpTypeQuery':
query_params['experimentalMethod'] = search_term
query_params['description'] = 'Experimental Method Search : Experimental Method='+ search_term
query_params['mvStructure.expMethod.value']= search_term
elif querytype=='PubmedIdQuery':
query_params['description'] = 'Pubmed Id Search for Pubmed Id '+ search_term
query_params['pubMedIdList'] = search_term
scan_params = dict()
scan_params['orgPdbQuery'] = query_params
return scan_params | [
"def",
"make_query",
"(",
"search_term",
",",
"querytype",
"=",
"'AdvancedKeywordQuery'",
")",
":",
"assert",
"querytype",
"in",
"{",
"'HoldingsQuery'",
",",
"'ExpTypeQuery'",
",",
"'AdvancedKeywordQuery'",
",",
"'StructureIdQuery'",
",",
"'ModifiedStructuresQuery'",
",... | Repackage strings into a search dictionary
This function takes a list of search terms and specifications
and repackages it as a dictionary object that can be used to conduct a search
Parameters
----------
search_term : str
The specific term to search in the database. For specific query types,
the strings that will yield valid results are limited to:
'HoldingsQuery' : A Ggeneral search of the metadata associated with PDB IDs
'ExpTypeQuery' : Experimental Method such as 'X-RAY', 'SOLID-STATE NMR', etc
'AdvancedKeywordQuery' : Any string that appears in the title or abstract
'StructureIdQuery' : Perform a search for a specific Structure ID
'ModifiedStructuresQuery' : Search for related structures
'AdvancedAuthorQuery' : Search by the names of authors associated with entries
'MotifQuery' : Search for a specific motif
'NoLigandQuery' : Find full list of PDB IDs without free ligrands
querytype : str
The type of query to perform, the easiest is an AdvancedKeywordQuery but more
specific types of searches may also be performed
Returns
-------
scan_params : dict
A dictionary representing the query
Examples
--------
This method usually gets used in tandem with do_search
>>> a = make_query('actin network')
>>> print (a)
{'orgPdbQuery': {'description': 'Text Search for: actin',
'keywords': 'actin',
'queryType': 'AdvancedKeywordQuery'}}
>>> search_dict = make_query('actin network')
>>> found_pdbs = do_search(search_dict)
>>> print(found_pdbs)
['1D7M', '3W3D', '4A7H', '4A7L', '4A7N']
>>> search_dict = make_query('T[AG]AGGY',querytype='MotifQuery')
>>> found_pdbs = do_search(search_dict)
>>> print(found_pdbs)
['3LEZ', '3SGH', '4F47'] | [
"Repackage",
"strings",
"into",
"a",
"search",
"dictionary"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L51-L159 | train | 23,130 |
williamgilpin/pypdb | pypdb/pypdb.py | do_protsym_search | def do_protsym_search(point_group, min_rmsd=0.0, max_rmsd=7.0):
'''Performs a protein symmetry search of the PDB
This function can search the Protein Data Bank based on how closely entries
match the user-specified symmetry group
Parameters
----------
point_group : str
The name of the symmetry point group to search. This includes all the standard
abbreviations for symmetry point groups (e.g., C1, C2, D2, T, O, I, H, A1)
min_rmsd : float
The smallest allowed total deviation (in Angstroms) for a result to be classified
as having a matching symmetry
max_rmsd : float
The largest allowed total deviation (in Angstroms) for a result to be classified
as having a matching symmetry
Returns
-------
idlist : list of strings
A list of PDB IDs resulting from the search
Examples
--------
>>> kk = do_protsym_search('C9', min_rmsd=0.0, max_rmsd=1.0)
>>> print(kk[:5])
['1KZU', '1NKZ', '2FKW', '3B8M', '3B8N']
'''
query_params = dict()
query_params['queryType'] = 'PointGroupQuery'
query_params['rMSDComparator'] = 'between'
query_params['pointGroup'] = point_group
query_params['rMSDMin'] = min_rmsd
query_params['rMSDMax'] = max_rmsd
scan_params = dict()
scan_params['orgPdbQuery'] = query_params
idlist = do_search(scan_params)
return idlist | python | def do_protsym_search(point_group, min_rmsd=0.0, max_rmsd=7.0):
'''Performs a protein symmetry search of the PDB
This function can search the Protein Data Bank based on how closely entries
match the user-specified symmetry group
Parameters
----------
point_group : str
The name of the symmetry point group to search. This includes all the standard
abbreviations for symmetry point groups (e.g., C1, C2, D2, T, O, I, H, A1)
min_rmsd : float
The smallest allowed total deviation (in Angstroms) for a result to be classified
as having a matching symmetry
max_rmsd : float
The largest allowed total deviation (in Angstroms) for a result to be classified
as having a matching symmetry
Returns
-------
idlist : list of strings
A list of PDB IDs resulting from the search
Examples
--------
>>> kk = do_protsym_search('C9', min_rmsd=0.0, max_rmsd=1.0)
>>> print(kk[:5])
['1KZU', '1NKZ', '2FKW', '3B8M', '3B8N']
'''
query_params = dict()
query_params['queryType'] = 'PointGroupQuery'
query_params['rMSDComparator'] = 'between'
query_params['pointGroup'] = point_group
query_params['rMSDMin'] = min_rmsd
query_params['rMSDMax'] = max_rmsd
scan_params = dict()
scan_params['orgPdbQuery'] = query_params
idlist = do_search(scan_params)
return idlist | [
"def",
"do_protsym_search",
"(",
"point_group",
",",
"min_rmsd",
"=",
"0.0",
",",
"max_rmsd",
"=",
"7.0",
")",
":",
"query_params",
"=",
"dict",
"(",
")",
"query_params",
"[",
"'queryType'",
"]",
"=",
"'PointGroupQuery'",
"query_params",
"[",
"'rMSDComparator'",... | Performs a protein symmetry search of the PDB
This function can search the Protein Data Bank based on how closely entries
match the user-specified symmetry group
Parameters
----------
point_group : str
The name of the symmetry point group to search. This includes all the standard
abbreviations for symmetry point groups (e.g., C1, C2, D2, T, O, I, H, A1)
min_rmsd : float
The smallest allowed total deviation (in Angstroms) for a result to be classified
as having a matching symmetry
max_rmsd : float
The largest allowed total deviation (in Angstroms) for a result to be classified
as having a matching symmetry
Returns
-------
idlist : list of strings
A list of PDB IDs resulting from the search
Examples
--------
>>> kk = do_protsym_search('C9', min_rmsd=0.0, max_rmsd=1.0)
>>> print(kk[:5])
['1KZU', '1NKZ', '2FKW', '3B8M', '3B8N'] | [
"Performs",
"a",
"protein",
"symmetry",
"search",
"of",
"the",
"PDB"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L222-L270 | train | 23,131 |
williamgilpin/pypdb | pypdb/pypdb.py | get_all | def get_all():
"""Return a list of all PDB entries currently in the RCSB Protein Data Bank
Returns
-------
out : list of str
A list of all of the PDB IDs currently in the RCSB PDB
Examples
--------
>>> print(get_all()[:10])
['100D', '101D', '101M', '102D', '102L', '102M', '103D', '103L', '103M', '104D']
"""
url = 'http://www.rcsb.org/pdb/rest/getCurrent'
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
result = f.read()
assert result
kk = str(result)
p = re.compile('structureId=\"...."')
matches = p.findall(str(result))
out = list()
for item in matches:
out.append(item[-5:-1])
return out | python | def get_all():
"""Return a list of all PDB entries currently in the RCSB Protein Data Bank
Returns
-------
out : list of str
A list of all of the PDB IDs currently in the RCSB PDB
Examples
--------
>>> print(get_all()[:10])
['100D', '101D', '101M', '102D', '102L', '102M', '103D', '103L', '103M', '104D']
"""
url = 'http://www.rcsb.org/pdb/rest/getCurrent'
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
result = f.read()
assert result
kk = str(result)
p = re.compile('structureId=\"...."')
matches = p.findall(str(result))
out = list()
for item in matches:
out.append(item[-5:-1])
return out | [
"def",
"get_all",
"(",
")",
":",
"url",
"=",
"'http://www.rcsb.org/pdb/rest/getCurrent'",
"req",
"=",
"urllib",
".",
"request",
".",
"Request",
"(",
"url",
")",
"f",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"req",
")",
"result",
"=",
"f",
".",... | Return a list of all PDB entries currently in the RCSB Protein Data Bank
Returns
-------
out : list of str
A list of all of the PDB IDs currently in the RCSB PDB
Examples
--------
>>> print(get_all()[:10])
['100D', '101D', '101M', '102D', '102L', '102M', '103D', '103L', '103M', '104D'] | [
"Return",
"a",
"list",
"of",
"all",
"PDB",
"entries",
"currently",
"in",
"the",
"RCSB",
"Protein",
"Data",
"Bank"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L273-L305 | train | 23,132 |
williamgilpin/pypdb | pypdb/pypdb.py | get_info | def get_info(pdb_id, url_root='http://www.rcsb.org/pdb/rest/describeMol?structureId='):
'''Look up all information about a given PDB ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
url_root : string
The string root of the specific url for the request type
Returns
-------
out : OrderedDict
An ordered dictionary object corresponding to bare xml
'''
url = url_root + pdb_id
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
result = f.read()
assert result
out = xmltodict.parse(result,process_namespaces=True)
return out | python | def get_info(pdb_id, url_root='http://www.rcsb.org/pdb/rest/describeMol?structureId='):
'''Look up all information about a given PDB ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
url_root : string
The string root of the specific url for the request type
Returns
-------
out : OrderedDict
An ordered dictionary object corresponding to bare xml
'''
url = url_root + pdb_id
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
result = f.read()
assert result
out = xmltodict.parse(result,process_namespaces=True)
return out | [
"def",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/describeMol?structureId='",
")",
":",
"url",
"=",
"url_root",
"+",
"pdb_id",
"req",
"=",
"urllib",
".",
"request",
".",
"Request",
"(",
"url",
")",
"f",
"=",
"urllib",
".",
... | Look up all information about a given PDB ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
url_root : string
The string root of the specific url for the request type
Returns
-------
out : OrderedDict
An ordered dictionary object corresponding to bare xml | [
"Look",
"up",
"all",
"information",
"about",
"a",
"given",
"PDB",
"ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L313-L341 | train | 23,133 |
williamgilpin/pypdb | pypdb/pypdb.py | get_pdb_file | def get_pdb_file(pdb_id, filetype='pdb', compression=False):
'''Get the full PDB file associated with a PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
filetype: string
The file type.
'pdb' is the older file format,
'cif' is the newer replacement.
'xml' an also be obtained and parsed using the various xml tools included in PyPDB
'structfact' retrieves structure factors (only available for certain PDB entries)
compression : bool
Retrieve a compressed (gz) version of the file
Returns
-------
result : string
The string representing the full PDB file in the given format
Examples
--------
>>> pdb_file = get_pdb_file('4lza', filetype='cif', compression=True)
>>> print(pdb_file[:200])
data_4LZA
#
_entry.id 4LZA
#
_audit_conform.dict_name mmcif_pdbx.dic
_audit_conform.dict_version 4.032
_audit_conform.dict_location http://mmcif.pdb.org/dictionaries/ascii/mmcif_pdbx
'''
full_url = "https://files.rcsb.org/download/"
full_url += pdb_id
if (filetype == 'structfact'):
full_url += "-sf.cif"
else:
full_url += "." + filetype
if compression:
full_url += ".gz"
else:
pass
req = urllib.request.Request(full_url)
f = urllib.request.urlopen(req)
result = f.read()
if not compression:
result = result.decode('ascii')
else:
pass
return result | python | def get_pdb_file(pdb_id, filetype='pdb', compression=False):
'''Get the full PDB file associated with a PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
filetype: string
The file type.
'pdb' is the older file format,
'cif' is the newer replacement.
'xml' an also be obtained and parsed using the various xml tools included in PyPDB
'structfact' retrieves structure factors (only available for certain PDB entries)
compression : bool
Retrieve a compressed (gz) version of the file
Returns
-------
result : string
The string representing the full PDB file in the given format
Examples
--------
>>> pdb_file = get_pdb_file('4lza', filetype='cif', compression=True)
>>> print(pdb_file[:200])
data_4LZA
#
_entry.id 4LZA
#
_audit_conform.dict_name mmcif_pdbx.dic
_audit_conform.dict_version 4.032
_audit_conform.dict_location http://mmcif.pdb.org/dictionaries/ascii/mmcif_pdbx
'''
full_url = "https://files.rcsb.org/download/"
full_url += pdb_id
if (filetype == 'structfact'):
full_url += "-sf.cif"
else:
full_url += "." + filetype
if compression:
full_url += ".gz"
else:
pass
req = urllib.request.Request(full_url)
f = urllib.request.urlopen(req)
result = f.read()
if not compression:
result = result.decode('ascii')
else:
pass
return result | [
"def",
"get_pdb_file",
"(",
"pdb_id",
",",
"filetype",
"=",
"'pdb'",
",",
"compression",
"=",
"False",
")",
":",
"full_url",
"=",
"\"https://files.rcsb.org/download/\"",
"full_url",
"+=",
"pdb_id",
"if",
"(",
"filetype",
"==",
"'structfact'",
")",
":",
"full_url... | Get the full PDB file associated with a PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
filetype: string
The file type.
'pdb' is the older file format,
'cif' is the newer replacement.
'xml' an also be obtained and parsed using the various xml tools included in PyPDB
'structfact' retrieves structure factors (only available for certain PDB entries)
compression : bool
Retrieve a compressed (gz) version of the file
Returns
-------
result : string
The string representing the full PDB file in the given format
Examples
--------
>>> pdb_file = get_pdb_file('4lza', filetype='cif', compression=True)
>>> print(pdb_file[:200])
data_4LZA
#
_entry.id 4LZA
#
_audit_conform.dict_name mmcif_pdbx.dic
_audit_conform.dict_version 4.032
_audit_conform.dict_location http://mmcif.pdb.org/dictionaries/ascii/mmcif_pdbx | [
"Get",
"the",
"full",
"PDB",
"file",
"associated",
"with",
"a",
"PDB_ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L343-L406 | train | 23,134 |
williamgilpin/pypdb | pypdb/pypdb.py | get_all_info | def get_all_info(pdb_id):
'''A wrapper for get_info that cleans up the output slighly
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing all the information stored in the entry
Examples
--------
>>> all_info = get_all_info('4lza')
>>> print(all_info)
{'polymer': {'macroMolecule': {'@name': 'Adenine phosphoribosyltransferase', '
accession': {'@id': 'B0K969'}}, '@entityNr': '1', '@type': 'protein',
'polymerDescription': {'@description': 'Adenine phosphoribosyltransferase'},
'synonym': {'@name': 'APRT'}, '@length': '195', 'enzClass': {'@ec': '2.4.2.7'},
'chain': [{'@id': 'A'}, {'@id': 'B'}],
'Taxonomy': {'@name': 'Thermoanaerobacter pseudethanolicus ATCC 33223',
'@id': '340099'}, '@weight': '22023.9'}, 'id': '4LZA'}
>>> results = get_all_info('2F5N')
>>> first_polymer = results['polymer'][0]
>>> first_polymer['polymerDescription']
{'@description': "5'-D(*AP*GP*GP*TP*AP*GP*AP*CP*CP*TP*GP*GP*AP*CP*GP*C)-3'"}
'''
out = to_dict( get_info(pdb_id) )['molDescription']['structureId']
out = remove_at_sign(out)
return out | python | def get_all_info(pdb_id):
'''A wrapper for get_info that cleans up the output slighly
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing all the information stored in the entry
Examples
--------
>>> all_info = get_all_info('4lza')
>>> print(all_info)
{'polymer': {'macroMolecule': {'@name': 'Adenine phosphoribosyltransferase', '
accession': {'@id': 'B0K969'}}, '@entityNr': '1', '@type': 'protein',
'polymerDescription': {'@description': 'Adenine phosphoribosyltransferase'},
'synonym': {'@name': 'APRT'}, '@length': '195', 'enzClass': {'@ec': '2.4.2.7'},
'chain': [{'@id': 'A'}, {'@id': 'B'}],
'Taxonomy': {'@name': 'Thermoanaerobacter pseudethanolicus ATCC 33223',
'@id': '340099'}, '@weight': '22023.9'}, 'id': '4LZA'}
>>> results = get_all_info('2F5N')
>>> first_polymer = results['polymer'][0]
>>> first_polymer['polymerDescription']
{'@description': "5'-D(*AP*GP*GP*TP*AP*GP*AP*CP*CP*TP*GP*GP*AP*CP*GP*C)-3'"}
'''
out = to_dict( get_info(pdb_id) )['molDescription']['structureId']
out = remove_at_sign(out)
return out | [
"def",
"get_all_info",
"(",
"pdb_id",
")",
":",
"out",
"=",
"to_dict",
"(",
"get_info",
"(",
"pdb_id",
")",
")",
"[",
"'molDescription'",
"]",
"[",
"'structureId'",
"]",
"out",
"=",
"remove_at_sign",
"(",
"out",
")",
"return",
"out"
] | A wrapper for get_info that cleans up the output slighly
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing all the information stored in the entry
Examples
--------
>>> all_info = get_all_info('4lza')
>>> print(all_info)
{'polymer': {'macroMolecule': {'@name': 'Adenine phosphoribosyltransferase', '
accession': {'@id': 'B0K969'}}, '@entityNr': '1', '@type': 'protein',
'polymerDescription': {'@description': 'Adenine phosphoribosyltransferase'},
'synonym': {'@name': 'APRT'}, '@length': '195', 'enzClass': {'@ec': '2.4.2.7'},
'chain': [{'@id': 'A'}, {'@id': 'B'}],
'Taxonomy': {'@name': 'Thermoanaerobacter pseudethanolicus ATCC 33223',
'@id': '340099'}, '@weight': '22023.9'}, 'id': '4LZA'}
>>> results = get_all_info('2F5N')
>>> first_polymer = results['polymer'][0]
>>> first_polymer['polymerDescription']
{'@description': "5'-D(*AP*GP*GP*TP*AP*GP*AP*CP*CP*TP*GP*GP*AP*CP*GP*C)-3'"} | [
"A",
"wrapper",
"for",
"get_info",
"that",
"cleans",
"up",
"the",
"output",
"slighly"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L409-L445 | train | 23,135 |
williamgilpin/pypdb | pypdb/pypdb.py | get_raw_blast | def get_raw_blast(pdb_id, output_form='HTML', chain_id='A'):
'''Look up full BLAST page for a given PDB ID
get_blast() uses this function internally
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
chain_id : string
A single character designating the chain ID of interest
output_form : string
TXT, HTML, or XML formatting of the outputs
Returns
-------
out : OrderedDict
An ordered dictionary object corresponding to bare xml
'''
url_root = 'http://www.rcsb.org/pdb/rest/getBlastPDB2?structureId='
url = url_root + pdb_id + '&chainId='+ chain_id +'&outputFormat=' + output_form
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
result = f.read()
result = result.decode('unicode_escape')
assert result
return result | python | def get_raw_blast(pdb_id, output_form='HTML', chain_id='A'):
'''Look up full BLAST page for a given PDB ID
get_blast() uses this function internally
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
chain_id : string
A single character designating the chain ID of interest
output_form : string
TXT, HTML, or XML formatting of the outputs
Returns
-------
out : OrderedDict
An ordered dictionary object corresponding to bare xml
'''
url_root = 'http://www.rcsb.org/pdb/rest/getBlastPDB2?structureId='
url = url_root + pdb_id + '&chainId='+ chain_id +'&outputFormat=' + output_form
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
result = f.read()
result = result.decode('unicode_escape')
assert result
return result | [
"def",
"get_raw_blast",
"(",
"pdb_id",
",",
"output_form",
"=",
"'HTML'",
",",
"chain_id",
"=",
"'A'",
")",
":",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/getBlastPDB2?structureId='",
"url",
"=",
"url_root",
"+",
"pdb_id",
"+",
"'&chainId='",
"+",
"chain_id",
... | Look up full BLAST page for a given PDB ID
get_blast() uses this function internally
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
chain_id : string
A single character designating the chain ID of interest
output_form : string
TXT, HTML, or XML formatting of the outputs
Returns
-------
out : OrderedDict
An ordered dictionary object corresponding to bare xml | [
"Look",
"up",
"full",
"BLAST",
"page",
"for",
"a",
"given",
"PDB",
"ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L447-L481 | train | 23,136 |
williamgilpin/pypdb | pypdb/pypdb.py | parse_blast | def parse_blast(blast_string):
'''Clean up HTML BLAST results
This function requires BeautifulSoup and the re module
It goes throught the complicated output returned by the BLAST
search and provides a list of matches, as well as the raw
text file showing the alignments for each of the matches.
This function works best with HTML formatted Inputs
------
get_blast() uses this function internally
Parameters
----------
blast_string : str
A complete webpage of standard BLAST results
Returns
-------
out : 2-tuple
A tuple consisting of a list of PDB matches, and a list
of their alignment text files (unformatted)
'''
soup = BeautifulSoup(str(blast_string), "html.parser")
all_blasts = list()
all_blast_ids = list()
pattern = '></a>....:'
prog = re.compile(pattern)
for item in soup.find_all('pre'):
if len(item.find_all('a'))==1:
all_blasts.append(item)
blast_id = re.findall(pattern, str(item) )[0][-5:-1]
all_blast_ids.append(blast_id)
out = (all_blast_ids, all_blasts)
return out | python | def parse_blast(blast_string):
'''Clean up HTML BLAST results
This function requires BeautifulSoup and the re module
It goes throught the complicated output returned by the BLAST
search and provides a list of matches, as well as the raw
text file showing the alignments for each of the matches.
This function works best with HTML formatted Inputs
------
get_blast() uses this function internally
Parameters
----------
blast_string : str
A complete webpage of standard BLAST results
Returns
-------
out : 2-tuple
A tuple consisting of a list of PDB matches, and a list
of their alignment text files (unformatted)
'''
soup = BeautifulSoup(str(blast_string), "html.parser")
all_blasts = list()
all_blast_ids = list()
pattern = '></a>....:'
prog = re.compile(pattern)
for item in soup.find_all('pre'):
if len(item.find_all('a'))==1:
all_blasts.append(item)
blast_id = re.findall(pattern, str(item) )[0][-5:-1]
all_blast_ids.append(blast_id)
out = (all_blast_ids, all_blasts)
return out | [
"def",
"parse_blast",
"(",
"blast_string",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"str",
"(",
"blast_string",
")",
",",
"\"html.parser\"",
")",
"all_blasts",
"=",
"list",
"(",
")",
"all_blast_ids",
"=",
"list",
"(",
")",
"pattern",
"=",
"'></a>....:'",... | Clean up HTML BLAST results
This function requires BeautifulSoup and the re module
It goes throught the complicated output returned by the BLAST
search and provides a list of matches, as well as the raw
text file showing the alignments for each of the matches.
This function works best with HTML formatted Inputs
------
get_blast() uses this function internally
Parameters
----------
blast_string : str
A complete webpage of standard BLAST results
Returns
-------
out : 2-tuple
A tuple consisting of a list of PDB matches, and a list
of their alignment text files (unformatted) | [
"Clean",
"up",
"HTML",
"BLAST",
"results"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L484-L528 | train | 23,137 |
williamgilpin/pypdb | pypdb/pypdb.py | get_blast2 | def get_blast2(pdb_id, chain_id='A', output_form='HTML'):
'''Alternative way to look up BLAST for a given PDB ID. This function is a wrapper
for get_raw_blast and parse_blast
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
chain_id : string
A single character designating the chain ID of interest
output_form : string
TXT, HTML, or XML formatting of the BLAST page
Returns
-------
out : 2-tuple
A tuple consisting of a list of PDB matches, and a list
of their alignment text files (unformatted)
Examples
--------
>>> blast_results = get_blast2('2F5N', chain_id='A', output_form='HTML')
>>> print('Total Results: ' + str(len(blast_results[0])) +'\n')
>>> print(blast_results[1][0])
Total Results: 84
<pre>
><a name="45354"></a>2F5P:3:A|pdbid|entity|chain(s)|sequence
Length = 274
Score = 545 bits (1404), Expect = e-155, Method: Composition-based stats.
Identities = 274/274 (100%), Positives = 274/274 (100%)
Query: 1 MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK 60
MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK
Sbjct: 1 MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK 60
...
'''
raw_results = get_raw_blast(pdb_id, chain_id=chain_id, output_form=output_form)
out = parse_blast(raw_results)
return out | python | def get_blast2(pdb_id, chain_id='A', output_form='HTML'):
'''Alternative way to look up BLAST for a given PDB ID. This function is a wrapper
for get_raw_blast and parse_blast
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
chain_id : string
A single character designating the chain ID of interest
output_form : string
TXT, HTML, or XML formatting of the BLAST page
Returns
-------
out : 2-tuple
A tuple consisting of a list of PDB matches, and a list
of their alignment text files (unformatted)
Examples
--------
>>> blast_results = get_blast2('2F5N', chain_id='A', output_form='HTML')
>>> print('Total Results: ' + str(len(blast_results[0])) +'\n')
>>> print(blast_results[1][0])
Total Results: 84
<pre>
><a name="45354"></a>2F5P:3:A|pdbid|entity|chain(s)|sequence
Length = 274
Score = 545 bits (1404), Expect = e-155, Method: Composition-based stats.
Identities = 274/274 (100%), Positives = 274/274 (100%)
Query: 1 MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK 60
MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK
Sbjct: 1 MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK 60
...
'''
raw_results = get_raw_blast(pdb_id, chain_id=chain_id, output_form=output_form)
out = parse_blast(raw_results)
return out | [
"def",
"get_blast2",
"(",
"pdb_id",
",",
"chain_id",
"=",
"'A'",
",",
"output_form",
"=",
"'HTML'",
")",
":",
"raw_results",
"=",
"get_raw_blast",
"(",
"pdb_id",
",",
"chain_id",
"=",
"chain_id",
",",
"output_form",
"=",
"output_form",
")",
"out",
"=",
"pa... | Alternative way to look up BLAST for a given PDB ID. This function is a wrapper
for get_raw_blast and parse_blast
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
chain_id : string
A single character designating the chain ID of interest
output_form : string
TXT, HTML, or XML formatting of the BLAST page
Returns
-------
out : 2-tuple
A tuple consisting of a list of PDB matches, and a list
of their alignment text files (unformatted)
Examples
--------
>>> blast_results = get_blast2('2F5N', chain_id='A', output_form='HTML')
>>> print('Total Results: ' + str(len(blast_results[0])) +'\n')
>>> print(blast_results[1][0])
Total Results: 84
<pre>
><a name="45354"></a>2F5P:3:A|pdbid|entity|chain(s)|sequence
Length = 274
Score = 545 bits (1404), Expect = e-155, Method: Composition-based stats.
Identities = 274/274 (100%), Positives = 274/274 (100%)
Query: 1 MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK 60
MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK
Sbjct: 1 MPELPEVETIRRTLLPLIVGKTIEDVRIFWPNIIRHPRDSEAFAARMIGQTVRGLERRGK 60
... | [
"Alternative",
"way",
"to",
"look",
"up",
"BLAST",
"for",
"a",
"given",
"PDB",
"ID",
".",
"This",
"function",
"is",
"a",
"wrapper",
"for",
"get_raw_blast",
"and",
"parse_blast"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L531-L576 | train | 23,138 |
williamgilpin/pypdb | pypdb/pypdb.py | describe_pdb | def describe_pdb(pdb_id):
"""Get description and metadata of a PDB entry
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : string
A text pdb description from PDB
Examples
--------
>>> describe_pdb('4lza')
{'citation_authors': 'Malashkevich, V.N., Bhosle, R., Toro, R., Hillerich, B., Gizzi, A., Garforth, S., Kar, A., Chan, M.K., Lafluer, J., Patel, H., Matikainen, B., Chamala, S., Lim, S., Celikgil, A., Villegas, G., Evans, B., Love, J., Fiser, A., Khafizov, K., Seidel, R., Bonanno, J.B., Almo, S.C.',
'deposition_date': '2013-07-31',
'expMethod': 'X-RAY DIFFRACTION',
'keywords': 'TRANSFERASE',
'last_modification_date': '2013-08-14',
'nr_atoms': '0',
'nr_entities': '1',
'nr_residues': '390',
'release_date': '2013-08-14',
'resolution': '1.84',
'status': 'CURRENT',
'structureId': '4LZA',
'structure_authors': 'Malashkevich, V.N., Bhosle, R., Toro, R., Hillerich, B., Gizzi, A., Garforth, S., Kar, A., Chan, M.K., Lafluer, J., Patel, H., Matikainen, B., Chamala, S., Lim, S., Celikgil, A., Villegas, G., Evans, B., Love, J., Fiser, A., Khafizov, K., Seidel, R., Bonanno, J.B., Almo, S.C., New York Structural Genomics Research Consortium (NYSGRC)',
'title': 'Crystal structure of adenine phosphoribosyltransferase from Thermoanaerobacter pseudethanolicus ATCC 33223, NYSGRC Target 029700.'}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/describePDB?structureId=')
out = to_dict(out)
out = remove_at_sign(out['PDBdescription']['PDB'])
return out | python | def describe_pdb(pdb_id):
"""Get description and metadata of a PDB entry
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : string
A text pdb description from PDB
Examples
--------
>>> describe_pdb('4lza')
{'citation_authors': 'Malashkevich, V.N., Bhosle, R., Toro, R., Hillerich, B., Gizzi, A., Garforth, S., Kar, A., Chan, M.K., Lafluer, J., Patel, H., Matikainen, B., Chamala, S., Lim, S., Celikgil, A., Villegas, G., Evans, B., Love, J., Fiser, A., Khafizov, K., Seidel, R., Bonanno, J.B., Almo, S.C.',
'deposition_date': '2013-07-31',
'expMethod': 'X-RAY DIFFRACTION',
'keywords': 'TRANSFERASE',
'last_modification_date': '2013-08-14',
'nr_atoms': '0',
'nr_entities': '1',
'nr_residues': '390',
'release_date': '2013-08-14',
'resolution': '1.84',
'status': 'CURRENT',
'structureId': '4LZA',
'structure_authors': 'Malashkevich, V.N., Bhosle, R., Toro, R., Hillerich, B., Gizzi, A., Garforth, S., Kar, A., Chan, M.K., Lafluer, J., Patel, H., Matikainen, B., Chamala, S., Lim, S., Celikgil, A., Villegas, G., Evans, B., Love, J., Fiser, A., Khafizov, K., Seidel, R., Bonanno, J.B., Almo, S.C., New York Structural Genomics Research Consortium (NYSGRC)',
'title': 'Crystal structure of adenine phosphoribosyltransferase from Thermoanaerobacter pseudethanolicus ATCC 33223, NYSGRC Target 029700.'}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/describePDB?structureId=')
out = to_dict(out)
out = remove_at_sign(out['PDBdescription']['PDB'])
return out | [
"def",
"describe_pdb",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/describePDB?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"out",
"=",
"remove_at_sign",
"(",
"out",
"[",
... | Get description and metadata of a PDB entry
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : string
A text pdb description from PDB
Examples
--------
>>> describe_pdb('4lza')
{'citation_authors': 'Malashkevich, V.N., Bhosle, R., Toro, R., Hillerich, B., Gizzi, A., Garforth, S., Kar, A., Chan, M.K., Lafluer, J., Patel, H., Matikainen, B., Chamala, S., Lim, S., Celikgil, A., Villegas, G., Evans, B., Love, J., Fiser, A., Khafizov, K., Seidel, R., Bonanno, J.B., Almo, S.C.',
'deposition_date': '2013-07-31',
'expMethod': 'X-RAY DIFFRACTION',
'keywords': 'TRANSFERASE',
'last_modification_date': '2013-08-14',
'nr_atoms': '0',
'nr_entities': '1',
'nr_residues': '390',
'release_date': '2013-08-14',
'resolution': '1.84',
'status': 'CURRENT',
'structureId': '4LZA',
'structure_authors': 'Malashkevich, V.N., Bhosle, R., Toro, R., Hillerich, B., Gizzi, A., Garforth, S., Kar, A., Chan, M.K., Lafluer, J., Patel, H., Matikainen, B., Chamala, S., Lim, S., Celikgil, A., Villegas, G., Evans, B., Love, J., Fiser, A., Khafizov, K., Seidel, R., Bonanno, J.B., Almo, S.C., New York Structural Genomics Research Consortium (NYSGRC)',
'title': 'Crystal structure of adenine phosphoribosyltransferase from Thermoanaerobacter pseudethanolicus ATCC 33223, NYSGRC Target 029700.'} | [
"Get",
"description",
"and",
"metadata",
"of",
"a",
"PDB",
"entry"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L578-L615 | train | 23,139 |
williamgilpin/pypdb | pypdb/pypdb.py | get_entity_info | def get_entity_info(pdb_id):
"""Return pdb id information
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing a description the entry
Examples
--------
>>> get_entity_info('4lza')
{'Entity': {'@id': '1',
'@type': 'protein',
'Chain': [{'@id': 'A'}, {'@id': 'B'}]},
'Method': {'@name': 'xray'},
'bioAssemblies': '1',
'release_date': 'Wed Aug 14 00:00:00 PDT 2013',
'resolution': '1.84',
'structureId': '4lza'}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/getEntityInfo?structureId=')
out = to_dict(out)
return remove_at_sign( out['entityInfo']['PDB'] ) | python | def get_entity_info(pdb_id):
"""Return pdb id information
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing a description the entry
Examples
--------
>>> get_entity_info('4lza')
{'Entity': {'@id': '1',
'@type': 'protein',
'Chain': [{'@id': 'A'}, {'@id': 'B'}]},
'Method': {'@name': 'xray'},
'bioAssemblies': '1',
'release_date': 'Wed Aug 14 00:00:00 PDT 2013',
'resolution': '1.84',
'structureId': '4lza'}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/getEntityInfo?structureId=')
out = to_dict(out)
return remove_at_sign( out['entityInfo']['PDB'] ) | [
"def",
"get_entity_info",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/getEntityInfo?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"return",
"remove_at_sign",
"(",
"out",
"[",
... | Return pdb id information
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing a description the entry
Examples
--------
>>> get_entity_info('4lza')
{'Entity': {'@id': '1',
'@type': 'protein',
'Chain': [{'@id': 'A'}, {'@id': 'B'}]},
'Method': {'@name': 'xray'},
'bioAssemblies': '1',
'release_date': 'Wed Aug 14 00:00:00 PDT 2013',
'resolution': '1.84',
'structureId': '4lza'} | [
"Return",
"pdb",
"id",
"information"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L617-L647 | train | 23,140 |
williamgilpin/pypdb | pypdb/pypdb.py | get_ligands | def get_ligands(pdb_id):
"""Return ligands of given PDB ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing a list of ligands associated with the entry
Examples
--------
>>> ligand_dict = get_ligands('100D')
>>> print(ligand_dict)
{'id': '100D',
'ligandInfo': {'ligand': {'@chemicalID': 'SPM',
'@molecularWeight': '202.34',
'@structureId': '100D',
'@type': 'non-polymer',
'InChI': 'InChI=1S/C10H26N4/c11-5-3-9-13-7-1-2-8-14-10-4-6-12/h13-14H,1-12H2',
'InChIKey': 'PFNFFQXMRSDOHW-UHFFFAOYSA-N',
'chemicalName': 'SPERMINE',
'formula': 'C10 H26 N4',
'smiles': 'C(CCNCCCN)CNCCCN'}}}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/ligandInfo?structureId=')
out = to_dict(out)
return remove_at_sign(out['structureId']) | python | def get_ligands(pdb_id):
"""Return ligands of given PDB ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing a list of ligands associated with the entry
Examples
--------
>>> ligand_dict = get_ligands('100D')
>>> print(ligand_dict)
{'id': '100D',
'ligandInfo': {'ligand': {'@chemicalID': 'SPM',
'@molecularWeight': '202.34',
'@structureId': '100D',
'@type': 'non-polymer',
'InChI': 'InChI=1S/C10H26N4/c11-5-3-9-13-7-1-2-8-14-10-4-6-12/h13-14H,1-12H2',
'InChIKey': 'PFNFFQXMRSDOHW-UHFFFAOYSA-N',
'chemicalName': 'SPERMINE',
'formula': 'C10 H26 N4',
'smiles': 'C(CCNCCCN)CNCCCN'}}}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/ligandInfo?structureId=')
out = to_dict(out)
return remove_at_sign(out['structureId']) | [
"def",
"get_ligands",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/ligandInfo?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"return",
"remove_at_sign",
"(",
"out",
"[",
"'stru... | Return ligands of given PDB ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing a list of ligands associated with the entry
Examples
--------
>>> ligand_dict = get_ligands('100D')
>>> print(ligand_dict)
{'id': '100D',
'ligandInfo': {'ligand': {'@chemicalID': 'SPM',
'@molecularWeight': '202.34',
'@structureId': '100D',
'@type': 'non-polymer',
'InChI': 'InChI=1S/C10H26N4/c11-5-3-9-13-7-1-2-8-14-10-4-6-12/h13-14H,1-12H2',
'InChIKey': 'PFNFFQXMRSDOHW-UHFFFAOYSA-N',
'chemicalName': 'SPERMINE',
'formula': 'C10 H26 N4',
'smiles': 'C(CCNCCCN)CNCCCN'}}} | [
"Return",
"ligands",
"of",
"given",
"PDB",
"ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L681-L715 | train | 23,141 |
williamgilpin/pypdb | pypdb/pypdb.py | get_gene_onto | def get_gene_onto(pdb_id):
"""Return ligands of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the gene ontology information associated with the entry
Examples
--------
>>> gene_info = get_gene_onto('4Z0L')
>>> print(gene_info['term'][0])
{'@chainId': 'A',
'@id': 'GO:0001516',
'@structureId': '4Z0L',
'detail': {'@definition': 'The chemical reactions and pathways resulting '
'in the formation of prostaglandins, any of a '
'group of biologically active metabolites which '
'contain a cyclopentane ring.',
'@name': 'prostaglandin biosynthetic process',
'@ontology': 'B',
'@synonyms': 'prostaglandin anabolism, prostaglandin '
'biosynthesis, prostaglandin formation, '
'prostaglandin synthesis'}}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/goTerms?structureId=')
out = to_dict(out)
if not out['goTerms']:
return None
out = remove_at_sign(out['goTerms'])
return out | python | def get_gene_onto(pdb_id):
"""Return ligands of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the gene ontology information associated with the entry
Examples
--------
>>> gene_info = get_gene_onto('4Z0L')
>>> print(gene_info['term'][0])
{'@chainId': 'A',
'@id': 'GO:0001516',
'@structureId': '4Z0L',
'detail': {'@definition': 'The chemical reactions and pathways resulting '
'in the formation of prostaglandins, any of a '
'group of biologically active metabolites which '
'contain a cyclopentane ring.',
'@name': 'prostaglandin biosynthetic process',
'@ontology': 'B',
'@synonyms': 'prostaglandin anabolism, prostaglandin '
'biosynthesis, prostaglandin formation, '
'prostaglandin synthesis'}}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/goTerms?structureId=')
out = to_dict(out)
if not out['goTerms']:
return None
out = remove_at_sign(out['goTerms'])
return out | [
"def",
"get_gene_onto",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/goTerms?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"if",
"not",
"out",
"[",
"'goTerms'",
"]",
":",
... | Return ligands of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the gene ontology information associated with the entry
Examples
--------
>>> gene_info = get_gene_onto('4Z0L')
>>> print(gene_info['term'][0])
{'@chainId': 'A',
'@id': 'GO:0001516',
'@structureId': '4Z0L',
'detail': {'@definition': 'The chemical reactions and pathways resulting '
'in the formation of prostaglandins, any of a '
'group of biologically active metabolites which '
'contain a cyclopentane ring.',
'@name': 'prostaglandin biosynthetic process',
'@ontology': 'B',
'@synonyms': 'prostaglandin anabolism, prostaglandin '
'biosynthesis, prostaglandin formation, '
'prostaglandin synthesis'}} | [
"Return",
"ligands",
"of",
"given",
"PDB_ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L717-L755 | train | 23,142 |
williamgilpin/pypdb | pypdb/pypdb.py | get_seq_cluster | def get_seq_cluster(pdb_id_chain):
"""Get the sequence cluster of a PDB ID plus a pdb_id plus a chain,
Parameters
----------
pdb_id_chain : string
A string denoting a 4 character PDB ID plus a one character chain
offset with a dot: XXXX.X, as in 2F5N.A
Returns
-------
out : dict
A dictionary containing the sequence cluster associated with the PDB
entry and chain
Examples
--------
>>> sclust = get_seq_cluster('2F5N.A')
>>> print(sclust['pdbChain'][:10])
[{'@name': '4PD2.A', '@rank': '1'},
{'@name': '3U6P.A', '@rank': '2'},
{'@name': '4PCZ.A', '@rank': '3'},
{'@name': '3GPU.A', '@rank': '4'},
{'@name': '3JR5.A', '@rank': '5'},
{'@name': '3SAU.A', '@rank': '6'},
{'@name': '3GQ4.A', '@rank': '7'},
{'@name': '1R2Z.A', '@rank': '8'},
{'@name': '3U6E.A', '@rank': '9'},
{'@name': '2XZF.A', '@rank': '10'}]
"""
url_root = 'http://www.rcsb.org/pdb/rest/sequenceCluster?structureId='
out = get_info(pdb_id_chain, url_root = url_root)
out = to_dict(out)
return remove_at_sign(out['sequenceCluster']) | python | def get_seq_cluster(pdb_id_chain):
"""Get the sequence cluster of a PDB ID plus a pdb_id plus a chain,
Parameters
----------
pdb_id_chain : string
A string denoting a 4 character PDB ID plus a one character chain
offset with a dot: XXXX.X, as in 2F5N.A
Returns
-------
out : dict
A dictionary containing the sequence cluster associated with the PDB
entry and chain
Examples
--------
>>> sclust = get_seq_cluster('2F5N.A')
>>> print(sclust['pdbChain'][:10])
[{'@name': '4PD2.A', '@rank': '1'},
{'@name': '3U6P.A', '@rank': '2'},
{'@name': '4PCZ.A', '@rank': '3'},
{'@name': '3GPU.A', '@rank': '4'},
{'@name': '3JR5.A', '@rank': '5'},
{'@name': '3SAU.A', '@rank': '6'},
{'@name': '3GQ4.A', '@rank': '7'},
{'@name': '1R2Z.A', '@rank': '8'},
{'@name': '3U6E.A', '@rank': '9'},
{'@name': '2XZF.A', '@rank': '10'}]
"""
url_root = 'http://www.rcsb.org/pdb/rest/sequenceCluster?structureId='
out = get_info(pdb_id_chain, url_root = url_root)
out = to_dict(out)
return remove_at_sign(out['sequenceCluster']) | [
"def",
"get_seq_cluster",
"(",
"pdb_id_chain",
")",
":",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/sequenceCluster?structureId='",
"out",
"=",
"get_info",
"(",
"pdb_id_chain",
",",
"url_root",
"=",
"url_root",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"retu... | Get the sequence cluster of a PDB ID plus a pdb_id plus a chain,
Parameters
----------
pdb_id_chain : string
A string denoting a 4 character PDB ID plus a one character chain
offset with a dot: XXXX.X, as in 2F5N.A
Returns
-------
out : dict
A dictionary containing the sequence cluster associated with the PDB
entry and chain
Examples
--------
>>> sclust = get_seq_cluster('2F5N.A')
>>> print(sclust['pdbChain'][:10])
[{'@name': '4PD2.A', '@rank': '1'},
{'@name': '3U6P.A', '@rank': '2'},
{'@name': '4PCZ.A', '@rank': '3'},
{'@name': '3GPU.A', '@rank': '4'},
{'@name': '3JR5.A', '@rank': '5'},
{'@name': '3SAU.A', '@rank': '6'},
{'@name': '3GQ4.A', '@rank': '7'},
{'@name': '1R2Z.A', '@rank': '8'},
{'@name': '3U6E.A', '@rank': '9'},
{'@name': '2XZF.A', '@rank': '10'}] | [
"Get",
"the",
"sequence",
"cluster",
"of",
"a",
"PDB",
"ID",
"plus",
"a",
"pdb_id",
"plus",
"a",
"chain"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L757-L795 | train | 23,143 |
williamgilpin/pypdb | pypdb/pypdb.py | get_pfam | def get_pfam(pdb_id):
"""Return PFAM annotations of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the PFAM annotations for the specified PDB ID
Examples
--------
>>> pfam_info = get_pfam('2LME')
>>> print(pfam_info)
{'pfamHit': {'@pfamAcc': 'PF03895.10', '@pfamName': 'YadA_anchor',
'@structureId': '2LME', '@pdbResNumEnd': '105', '@pdbResNumStart': '28',
'@pfamDesc': 'YadA-like C-terminal region', '@eValue': '5.0E-22', '@chainId': 'A'}}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/hmmer?structureId=')
out = to_dict(out)
if not out['hmmer3']:
return dict()
return remove_at_sign(out['hmmer3']) | python | def get_pfam(pdb_id):
"""Return PFAM annotations of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the PFAM annotations for the specified PDB ID
Examples
--------
>>> pfam_info = get_pfam('2LME')
>>> print(pfam_info)
{'pfamHit': {'@pfamAcc': 'PF03895.10', '@pfamName': 'YadA_anchor',
'@structureId': '2LME', '@pdbResNumEnd': '105', '@pdbResNumStart': '28',
'@pfamDesc': 'YadA-like C-terminal region', '@eValue': '5.0E-22', '@chainId': 'A'}}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/hmmer?structureId=')
out = to_dict(out)
if not out['hmmer3']:
return dict()
return remove_at_sign(out['hmmer3']) | [
"def",
"get_pfam",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/hmmer?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"if",
"not",
"out",
"[",
"'hmmer3'",
"]",
":",
"return"... | Return PFAM annotations of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the PFAM annotations for the specified PDB ID
Examples
--------
>>> pfam_info = get_pfam('2LME')
>>> print(pfam_info)
{'pfamHit': {'@pfamAcc': 'PF03895.10', '@pfamName': 'YadA_anchor',
'@structureId': '2LME', '@pdbResNumEnd': '105', '@pdbResNumStart': '28',
'@pfamDesc': 'YadA-like C-terminal region', '@eValue': '5.0E-22', '@chainId': 'A'}} | [
"Return",
"PFAM",
"annotations",
"of",
"given",
"PDB_ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L844-L873 | train | 23,144 |
williamgilpin/pypdb | pypdb/pypdb.py | get_clusters | def get_clusters(pdb_id):
"""Return cluster related web services of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the representative clusters for the specified PDB ID
Examples
--------
>>> clusts = get_clusters('4hhb.A')
>>> print(clusts)
{'pdbChain': {'@name': '2W72.A'}}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/representatives?structureId=')
out = to_dict(out)
return remove_at_sign(out['representatives']) | python | def get_clusters(pdb_id):
"""Return cluster related web services of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the representative clusters for the specified PDB ID
Examples
--------
>>> clusts = get_clusters('4hhb.A')
>>> print(clusts)
{'pdbChain': {'@name': '2W72.A'}}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/representatives?structureId=')
out = to_dict(out)
return remove_at_sign(out['representatives']) | [
"def",
"get_clusters",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/representatives?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"return",
"remove_at_sign",
"(",
"out",
"[",
... | Return cluster related web services of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the representative clusters for the specified PDB ID
Examples
--------
>>> clusts = get_clusters('4hhb.A')
>>> print(clusts)
{'pdbChain': {'@name': '2W72.A'}} | [
"Return",
"cluster",
"related",
"web",
"services",
"of",
"given",
"PDB_ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L875-L900 | train | 23,145 |
williamgilpin/pypdb | pypdb/pypdb.py | find_results_gen | def find_results_gen(search_term, field='title'):
'''
Return a generator of the results returned by a search of
the protein data bank. This generator is used internally.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to record about each entry
Examples
--------
>>> result_gen = find_results_gen('bleb')
>>> pprint.pprint([item for item in result_gen][:5])
['MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-BEFX',
'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-ALF4',
'DICTYOSTELIUM DISCOIDEUM MYOSIN II MOTOR DOMAIN S456E WITH BOUND MGADP-BEFX',
'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456E BOUND WITH MGADP-ALF4',
'The structural basis of blebbistatin inhibition and specificity for myosin '
'II']
'''
scan_params = make_query(search_term, querytype='AdvancedKeywordQuery')
search_result_ids = do_search(scan_params)
all_titles = []
for pdb_result in search_result_ids:
result= describe_pdb(pdb_result)
if field in result.keys():
yield result[field] | python | def find_results_gen(search_term, field='title'):
'''
Return a generator of the results returned by a search of
the protein data bank. This generator is used internally.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to record about each entry
Examples
--------
>>> result_gen = find_results_gen('bleb')
>>> pprint.pprint([item for item in result_gen][:5])
['MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-BEFX',
'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-ALF4',
'DICTYOSTELIUM DISCOIDEUM MYOSIN II MOTOR DOMAIN S456E WITH BOUND MGADP-BEFX',
'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456E BOUND WITH MGADP-ALF4',
'The structural basis of blebbistatin inhibition and specificity for myosin '
'II']
'''
scan_params = make_query(search_term, querytype='AdvancedKeywordQuery')
search_result_ids = do_search(scan_params)
all_titles = []
for pdb_result in search_result_ids:
result= describe_pdb(pdb_result)
if field in result.keys():
yield result[field] | [
"def",
"find_results_gen",
"(",
"search_term",
",",
"field",
"=",
"'title'",
")",
":",
"scan_params",
"=",
"make_query",
"(",
"search_term",
",",
"querytype",
"=",
"'AdvancedKeywordQuery'",
")",
"search_result_ids",
"=",
"do_search",
"(",
"scan_params",
")",
"all_... | Return a generator of the results returned by a search of
the protein data bank. This generator is used internally.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to record about each entry
Examples
--------
>>> result_gen = find_results_gen('bleb')
>>> pprint.pprint([item for item in result_gen][:5])
['MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-BEFX',
'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-ALF4',
'DICTYOSTELIUM DISCOIDEUM MYOSIN II MOTOR DOMAIN S456E WITH BOUND MGADP-BEFX',
'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456E BOUND WITH MGADP-ALF4',
'The structural basis of blebbistatin inhibition and specificity for myosin '
'II'] | [
"Return",
"a",
"generator",
"of",
"the",
"results",
"returned",
"by",
"a",
"search",
"of",
"the",
"protein",
"data",
"bank",
".",
"This",
"generator",
"is",
"used",
"internally",
"."
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L904-L938 | train | 23,146 |
williamgilpin/pypdb | pypdb/pypdb.py | parse_results_gen | def parse_results_gen(search_term, field='title', max_results = 100, sleep_time=.1):
'''
Query the PDB with a search term and field while respecting the query frequency
limitations of the API.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to record about each entry
max_results : int
The maximum number of results to search through when
determining the top results
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
all_data_raw : list of str
'''
if max_results*sleep_time > 30:
warnings.warn("Because of API limitations, this function\
will take at least " + str(max_results*sleep_time) + " seconds to return results.\
If you need greater speed, try modifying the optional argument sleep_time=.1, (although \
this may cause the search to time out)" )
all_data_raw = find_results_gen(search_term, field=field)
all_data =list()
while len(all_data) < max_results:
all_data.append(all_data_raw.send(None))
time.sleep(sleep_time)
return all_data | python | def parse_results_gen(search_term, field='title', max_results = 100, sleep_time=.1):
'''
Query the PDB with a search term and field while respecting the query frequency
limitations of the API.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to record about each entry
max_results : int
The maximum number of results to search through when
determining the top results
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
all_data_raw : list of str
'''
if max_results*sleep_time > 30:
warnings.warn("Because of API limitations, this function\
will take at least " + str(max_results*sleep_time) + " seconds to return results.\
If you need greater speed, try modifying the optional argument sleep_time=.1, (although \
this may cause the search to time out)" )
all_data_raw = find_results_gen(search_term, field=field)
all_data =list()
while len(all_data) < max_results:
all_data.append(all_data_raw.send(None))
time.sleep(sleep_time)
return all_data | [
"def",
"parse_results_gen",
"(",
"search_term",
",",
"field",
"=",
"'title'",
",",
"max_results",
"=",
"100",
",",
"sleep_time",
"=",
".1",
")",
":",
"if",
"max_results",
"*",
"sleep_time",
">",
"30",
":",
"warnings",
".",
"warn",
"(",
"\"Because of API limi... | Query the PDB with a search term and field while respecting the query frequency
limitations of the API.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to record about each entry
max_results : int
The maximum number of results to search through when
determining the top results
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
all_data_raw : list of str | [
"Query",
"the",
"PDB",
"with",
"a",
"search",
"term",
"and",
"field",
"while",
"respecting",
"the",
"query",
"frequency",
"limitations",
"of",
"the",
"API",
"."
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L940-L982 | train | 23,147 |
williamgilpin/pypdb | pypdb/pypdb.py | find_papers | def find_papers(search_term, **kwargs):
'''
Return an ordered list of the top papers returned by a keyword search of
the RCSB PDB
Parameters
----------
search_term : str
The search keyword
max_results : int
The maximum number of results to return
Returns
-------
all_papers : list of strings
A descending-order list containing the top papers associated with
the search term in the PDB
Examples
--------
>>> matching_papers = find_papers('crispr',max_results=3)
>>> print(matching_papers)
['Crystal structure of a CRISPR-associated protein from thermus thermophilus',
'CRYSTAL STRUCTURE OF HYPOTHETICAL PROTEIN SSO1404 FROM SULFOLOBUS SOLFATARICUS P2',
'NMR solution structure of a CRISPR repeat binding protein']
'''
all_papers = parse_results_gen(search_term, field='title', **kwargs)
return remove_dupes(all_papers) | python | def find_papers(search_term, **kwargs):
'''
Return an ordered list of the top papers returned by a keyword search of
the RCSB PDB
Parameters
----------
search_term : str
The search keyword
max_results : int
The maximum number of results to return
Returns
-------
all_papers : list of strings
A descending-order list containing the top papers associated with
the search term in the PDB
Examples
--------
>>> matching_papers = find_papers('crispr',max_results=3)
>>> print(matching_papers)
['Crystal structure of a CRISPR-associated protein from thermus thermophilus',
'CRYSTAL STRUCTURE OF HYPOTHETICAL PROTEIN SSO1404 FROM SULFOLOBUS SOLFATARICUS P2',
'NMR solution structure of a CRISPR repeat binding protein']
'''
all_papers = parse_results_gen(search_term, field='title', **kwargs)
return remove_dupes(all_papers) | [
"def",
"find_papers",
"(",
"search_term",
",",
"*",
"*",
"kwargs",
")",
":",
"all_papers",
"=",
"parse_results_gen",
"(",
"search_term",
",",
"field",
"=",
"'title'",
",",
"*",
"*",
"kwargs",
")",
"return",
"remove_dupes",
"(",
"all_papers",
")"
] | Return an ordered list of the top papers returned by a keyword search of
the RCSB PDB
Parameters
----------
search_term : str
The search keyword
max_results : int
The maximum number of results to return
Returns
-------
all_papers : list of strings
A descending-order list containing the top papers associated with
the search term in the PDB
Examples
--------
>>> matching_papers = find_papers('crispr',max_results=3)
>>> print(matching_papers)
['Crystal structure of a CRISPR-associated protein from thermus thermophilus',
'CRYSTAL STRUCTURE OF HYPOTHETICAL PROTEIN SSO1404 FROM SULFOLOBUS SOLFATARICUS P2',
'NMR solution structure of a CRISPR repeat binding protein'] | [
"Return",
"an",
"ordered",
"list",
"of",
"the",
"top",
"papers",
"returned",
"by",
"a",
"keyword",
"search",
"of",
"the",
"RCSB",
"PDB"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L985-L1017 | train | 23,148 |
williamgilpin/pypdb | pypdb/pypdb.py | find_authors | def find_authors(search_term, **kwargs):
'''Return an ordered list of the top authors returned by a keyword search of
the RCSB PDB
This function is based on the number of unique PDB entries a given author has
his or her name associated with, and not author order or the ranking of the
entry in the keyword search results. So if an author tends to publish on topics
related to the search_term a lot, even if those papers are not the best match for
the exact search, he or she will have priority in this function over an author
who wrote the one paper that is most relevant to the search term. For the latter
option, just do a standard keyword search using do_search.
Parameters
----------
search_term : str
The search keyword
max_results : int
The maximum number of results to return
Returns
-------
out : list of str
Examples
--------
>>> top_authors = find_authors('crispr',max_results=100)
>>> print(top_authors[:10])
['Doudna, J.A.', 'Jinek, M.', 'Ke, A.', 'Li, H.', 'Nam, K.H.']
'''
all_individuals = parse_results_gen(search_term, field='citation_authors', **kwargs)
full_author_list = []
for individual in all_individuals:
individual = individual.replace('.,', '.;')
author_list_clean = [x.strip() for x in individual.split(';')]
full_author_list+=author_list_clean
out = list(chain.from_iterable(repeat(ii, c) for ii,c in Counter(full_author_list).most_common()))
return remove_dupes(out) | python | def find_authors(search_term, **kwargs):
'''Return an ordered list of the top authors returned by a keyword search of
the RCSB PDB
This function is based on the number of unique PDB entries a given author has
his or her name associated with, and not author order or the ranking of the
entry in the keyword search results. So if an author tends to publish on topics
related to the search_term a lot, even if those papers are not the best match for
the exact search, he or she will have priority in this function over an author
who wrote the one paper that is most relevant to the search term. For the latter
option, just do a standard keyword search using do_search.
Parameters
----------
search_term : str
The search keyword
max_results : int
The maximum number of results to return
Returns
-------
out : list of str
Examples
--------
>>> top_authors = find_authors('crispr',max_results=100)
>>> print(top_authors[:10])
['Doudna, J.A.', 'Jinek, M.', 'Ke, A.', 'Li, H.', 'Nam, K.H.']
'''
all_individuals = parse_results_gen(search_term, field='citation_authors', **kwargs)
full_author_list = []
for individual in all_individuals:
individual = individual.replace('.,', '.;')
author_list_clean = [x.strip() for x in individual.split(';')]
full_author_list+=author_list_clean
out = list(chain.from_iterable(repeat(ii, c) for ii,c in Counter(full_author_list).most_common()))
return remove_dupes(out) | [
"def",
"find_authors",
"(",
"search_term",
",",
"*",
"*",
"kwargs",
")",
":",
"all_individuals",
"=",
"parse_results_gen",
"(",
"search_term",
",",
"field",
"=",
"'citation_authors'",
",",
"*",
"*",
"kwargs",
")",
"full_author_list",
"=",
"[",
"]",
"for",
"i... | Return an ordered list of the top authors returned by a keyword search of
the RCSB PDB
This function is based on the number of unique PDB entries a given author has
his or her name associated with, and not author order or the ranking of the
entry in the keyword search results. So if an author tends to publish on topics
related to the search_term a lot, even if those papers are not the best match for
the exact search, he or she will have priority in this function over an author
who wrote the one paper that is most relevant to the search term. For the latter
option, just do a standard keyword search using do_search.
Parameters
----------
search_term : str
The search keyword
max_results : int
The maximum number of results to return
Returns
-------
out : list of str
Examples
--------
>>> top_authors = find_authors('crispr',max_results=100)
>>> print(top_authors[:10])
['Doudna, J.A.', 'Jinek, M.', 'Ke, A.', 'Li, H.', 'Nam, K.H.'] | [
"Return",
"an",
"ordered",
"list",
"of",
"the",
"top",
"authors",
"returned",
"by",
"a",
"keyword",
"search",
"of",
"the",
"RCSB",
"PDB"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L1019-L1065 | train | 23,149 |
williamgilpin/pypdb | pypdb/pypdb.py | list_taxa | def list_taxa(pdb_list, sleep_time=.1):
'''Given a list of PDB IDs, look up their associated species
This function digs through the search results returned
by the get_all_info() function and returns any information on
taxonomy included within the description.
The PDB website description of each entry includes the name
of the species (and sometimes details of organ or body part)
for each protein structure sample.
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
taxa : list of str
A list of the names or classifictions of species
associated with entries
Examples
--------
>>> crispr_query = make_query('crispr')
>>> crispr_results = do_search(crispr_query)
>>> print(list_taxa(crispr_results[:10]))
['Thermus thermophilus',
'Sulfolobus solfataricus P2',
'Hyperthermus butylicus DSM 5456',
'unidentified phage',
'Sulfolobus solfataricus P2',
'Pseudomonas aeruginosa UCBPP-PA14',
'Pseudomonas aeruginosa UCBPP-PA14',
'Pseudomonas aeruginosa UCBPP-PA14',
'Sulfolobus solfataricus',
'Thermus thermophilus HB8']
'''
if len(pdb_list)*sleep_time > 30:
warnings.warn("Because of API limitations, this function\
will take at least " + str(len(pdb_list)*sleep_time) + " seconds to return results.\
If you need greater speed, try modifying the optional argument sleep_time=.1, (although \
this may cause the search to time out)" )
taxa = []
for pdb_id in pdb_list:
all_info = get_all_info(pdb_id)
species_results = walk_nested_dict(all_info, 'Taxonomy', maxdepth=25,outputs=[])
first_result = walk_nested_dict(species_results,'@name',outputs=[])
if first_result:
taxa.append(first_result[-1])
else:
taxa.append('Unknown')
time.sleep(sleep_time)
return taxa | python | def list_taxa(pdb_list, sleep_time=.1):
'''Given a list of PDB IDs, look up their associated species
This function digs through the search results returned
by the get_all_info() function and returns any information on
taxonomy included within the description.
The PDB website description of each entry includes the name
of the species (and sometimes details of organ or body part)
for each protein structure sample.
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
taxa : list of str
A list of the names or classifictions of species
associated with entries
Examples
--------
>>> crispr_query = make_query('crispr')
>>> crispr_results = do_search(crispr_query)
>>> print(list_taxa(crispr_results[:10]))
['Thermus thermophilus',
'Sulfolobus solfataricus P2',
'Hyperthermus butylicus DSM 5456',
'unidentified phage',
'Sulfolobus solfataricus P2',
'Pseudomonas aeruginosa UCBPP-PA14',
'Pseudomonas aeruginosa UCBPP-PA14',
'Pseudomonas aeruginosa UCBPP-PA14',
'Sulfolobus solfataricus',
'Thermus thermophilus HB8']
'''
if len(pdb_list)*sleep_time > 30:
warnings.warn("Because of API limitations, this function\
will take at least " + str(len(pdb_list)*sleep_time) + " seconds to return results.\
If you need greater speed, try modifying the optional argument sleep_time=.1, (although \
this may cause the search to time out)" )
taxa = []
for pdb_id in pdb_list:
all_info = get_all_info(pdb_id)
species_results = walk_nested_dict(all_info, 'Taxonomy', maxdepth=25,outputs=[])
first_result = walk_nested_dict(species_results,'@name',outputs=[])
if first_result:
taxa.append(first_result[-1])
else:
taxa.append('Unknown')
time.sleep(sleep_time)
return taxa | [
"def",
"list_taxa",
"(",
"pdb_list",
",",
"sleep_time",
"=",
".1",
")",
":",
"if",
"len",
"(",
"pdb_list",
")",
"*",
"sleep_time",
">",
"30",
":",
"warnings",
".",
"warn",
"(",
"\"Because of API limitations, this function\\\n will take at least \"",
"+",
"s... | Given a list of PDB IDs, look up their associated species
This function digs through the search results returned
by the get_all_info() function and returns any information on
taxonomy included within the description.
The PDB website description of each entry includes the name
of the species (and sometimes details of organ or body part)
for each protein structure sample.
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
taxa : list of str
A list of the names or classifictions of species
associated with entries
Examples
--------
>>> crispr_query = make_query('crispr')
>>> crispr_results = do_search(crispr_query)
>>> print(list_taxa(crispr_results[:10]))
['Thermus thermophilus',
'Sulfolobus solfataricus P2',
'Hyperthermus butylicus DSM 5456',
'unidentified phage',
'Sulfolobus solfataricus P2',
'Pseudomonas aeruginosa UCBPP-PA14',
'Pseudomonas aeruginosa UCBPP-PA14',
'Pseudomonas aeruginosa UCBPP-PA14',
'Sulfolobus solfataricus',
'Thermus thermophilus HB8'] | [
"Given",
"a",
"list",
"of",
"PDB",
"IDs",
"look",
"up",
"their",
"associated",
"species"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L1095-L1162 | train | 23,150 |
williamgilpin/pypdb | pypdb/pypdb.py | list_types | def list_types(pdb_list, sleep_time=.1):
'''Given a list of PDB IDs, look up their associated structure type
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
infotypes : list of str
A list of the structure types associated with each PDB
in the list. For many entries in the RCSB PDB, this defaults
to 'protein'
Examples
--------
>>> crispr_query = make_query('crispr')
>>> crispr_results = do_search(crispr_query)
>>> print(list_types(crispr_results[:5]))
['protein', 'protein', 'protein', 'protein', 'protein']
'''
if len(pdb_list)*sleep_time > 30:
warnings.warn("Because of API limitations, this function\
will take at least " + str(len(pdb_list)*sleep_time) + " seconds to return results.\
If you need greater speed, try modifying the optional argument sleep_time=.1, (although \
this may cause the search to time out)" )
infotypes = []
for pdb_id in pdb_list:
all_info = get_all_info(pdb_id)
type_results = walk_nested_dict(all_info, '@type', maxdepth=25,outputs=[])
if type_results:
infotypes.append(type_results[-1])
else:
infotypes.append('Unknown')
time.sleep(sleep_time)
return infotypes | python | def list_types(pdb_list, sleep_time=.1):
'''Given a list of PDB IDs, look up their associated structure type
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
infotypes : list of str
A list of the structure types associated with each PDB
in the list. For many entries in the RCSB PDB, this defaults
to 'protein'
Examples
--------
>>> crispr_query = make_query('crispr')
>>> crispr_results = do_search(crispr_query)
>>> print(list_types(crispr_results[:5]))
['protein', 'protein', 'protein', 'protein', 'protein']
'''
if len(pdb_list)*sleep_time > 30:
warnings.warn("Because of API limitations, this function\
will take at least " + str(len(pdb_list)*sleep_time) + " seconds to return results.\
If you need greater speed, try modifying the optional argument sleep_time=.1, (although \
this may cause the search to time out)" )
infotypes = []
for pdb_id in pdb_list:
all_info = get_all_info(pdb_id)
type_results = walk_nested_dict(all_info, '@type', maxdepth=25,outputs=[])
if type_results:
infotypes.append(type_results[-1])
else:
infotypes.append('Unknown')
time.sleep(sleep_time)
return infotypes | [
"def",
"list_types",
"(",
"pdb_list",
",",
"sleep_time",
"=",
".1",
")",
":",
"if",
"len",
"(",
"pdb_list",
")",
"*",
"sleep_time",
">",
"30",
":",
"warnings",
".",
"warn",
"(",
"\"Because of API limitations, this function\\\n will take at least \"",
"+",
"... | Given a list of PDB IDs, look up their associated structure type
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
infotypes : list of str
A list of the structure types associated with each PDB
in the list. For many entries in the RCSB PDB, this defaults
to 'protein'
Examples
--------
>>> crispr_query = make_query('crispr')
>>> crispr_results = do_search(crispr_query)
>>> print(list_types(crispr_results[:5]))
['protein', 'protein', 'protein', 'protein', 'protein'] | [
"Given",
"a",
"list",
"of",
"PDB",
"IDs",
"look",
"up",
"their",
"associated",
"structure",
"type"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L1164-L1212 | train | 23,151 |
williamgilpin/pypdb | pypdb/pypdb.py | remove_dupes | def remove_dupes(list_with_dupes):
'''Remove duplicate entries from a list while preserving order
This function uses Python's standard equivalence testing methods in
order to determine if two elements of a list are identical. So if in the list [a,b,c]
the condition a == b is True, then regardless of whether a and b are strings, ints,
or other, then b will be removed from the list: [a, c]
Parameters
----------
list_with_dupes : list
A list containing duplicate elements
Returns
-------
out : list
The list with the duplicate entries removed by the order preserved
Examples
--------
>>> a = [1,3,2,4,2]
>>> print(remove_dupes(a))
[1,3,2,4]
'''
visited = set()
visited_add = visited.add
out = [ entry for entry in list_with_dupes if not (entry in visited or visited_add(entry))]
return out | python | def remove_dupes(list_with_dupes):
'''Remove duplicate entries from a list while preserving order
This function uses Python's standard equivalence testing methods in
order to determine if two elements of a list are identical. So if in the list [a,b,c]
the condition a == b is True, then regardless of whether a and b are strings, ints,
or other, then b will be removed from the list: [a, c]
Parameters
----------
list_with_dupes : list
A list containing duplicate elements
Returns
-------
out : list
The list with the duplicate entries removed by the order preserved
Examples
--------
>>> a = [1,3,2,4,2]
>>> print(remove_dupes(a))
[1,3,2,4]
'''
visited = set()
visited_add = visited.add
out = [ entry for entry in list_with_dupes if not (entry in visited or visited_add(entry))]
return out | [
"def",
"remove_dupes",
"(",
"list_with_dupes",
")",
":",
"visited",
"=",
"set",
"(",
")",
"visited_add",
"=",
"visited",
".",
"add",
"out",
"=",
"[",
"entry",
"for",
"entry",
"in",
"list_with_dupes",
"if",
"not",
"(",
"entry",
"in",
"visited",
"or",
"vis... | Remove duplicate entries from a list while preserving order
This function uses Python's standard equivalence testing methods in
order to determine if two elements of a list are identical. So if in the list [a,b,c]
the condition a == b is True, then regardless of whether a and b are strings, ints,
or other, then b will be removed from the list: [a, c]
Parameters
----------
list_with_dupes : list
A list containing duplicate elements
Returns
-------
out : list
The list with the duplicate entries removed by the order preserved
Examples
--------
>>> a = [1,3,2,4,2]
>>> print(remove_dupes(a))
[1,3,2,4] | [
"Remove",
"duplicate",
"entries",
"from",
"a",
"list",
"while",
"preserving",
"order"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L1268-L1298 | train | 23,152 |
ndrplz/google-drive-downloader | google_drive_downloader/google_drive_downloader.py | GoogleDriveDownloader.download_file_from_google_drive | def download_file_from_google_drive(file_id, dest_path, overwrite=False, unzip=False, showsize=False):
"""
Downloads a shared file from google drive into a given folder.
Optionally unzips it.
Parameters
----------
file_id: str
the file identifier.
You can obtain it from the sharable link.
dest_path: str
the destination where to save the downloaded file.
Must be a path (for example: './downloaded_file.txt')
overwrite: bool
optional, if True forces re-download and overwrite.
unzip: bool
optional, if True unzips a file.
If the file is not a zip file, ignores it.
showsize: bool
optional, if True print the current download size.
Returns
-------
None
"""
destination_directory = dirname(dest_path)
if not exists(destination_directory):
makedirs(destination_directory)
if not exists(dest_path) or overwrite:
session = requests.Session()
print('Downloading {} into {}... '.format(file_id, dest_path), end='')
stdout.flush()
response = session.get(GoogleDriveDownloader.DOWNLOAD_URL, params={'id': file_id}, stream=True)
token = GoogleDriveDownloader._get_confirm_token(response)
if token:
params = {'id': file_id, 'confirm': token}
response = session.get(GoogleDriveDownloader.DOWNLOAD_URL, params=params, stream=True)
if showsize:
print() # Skip to the next line
current_download_size = [0]
GoogleDriveDownloader._save_response_content(response, dest_path, showsize, current_download_size)
print('Done.')
if unzip:
try:
print('Unzipping...', end='')
stdout.flush()
with zipfile.ZipFile(dest_path, 'r') as z:
z.extractall(destination_directory)
print('Done.')
except zipfile.BadZipfile:
warnings.warn('Ignoring `unzip` since "{}" does not look like a valid zip file'.format(file_id)) | python | def download_file_from_google_drive(file_id, dest_path, overwrite=False, unzip=False, showsize=False):
"""
Downloads a shared file from google drive into a given folder.
Optionally unzips it.
Parameters
----------
file_id: str
the file identifier.
You can obtain it from the sharable link.
dest_path: str
the destination where to save the downloaded file.
Must be a path (for example: './downloaded_file.txt')
overwrite: bool
optional, if True forces re-download and overwrite.
unzip: bool
optional, if True unzips a file.
If the file is not a zip file, ignores it.
showsize: bool
optional, if True print the current download size.
Returns
-------
None
"""
destination_directory = dirname(dest_path)
if not exists(destination_directory):
makedirs(destination_directory)
if not exists(dest_path) or overwrite:
session = requests.Session()
print('Downloading {} into {}... '.format(file_id, dest_path), end='')
stdout.flush()
response = session.get(GoogleDriveDownloader.DOWNLOAD_URL, params={'id': file_id}, stream=True)
token = GoogleDriveDownloader._get_confirm_token(response)
if token:
params = {'id': file_id, 'confirm': token}
response = session.get(GoogleDriveDownloader.DOWNLOAD_URL, params=params, stream=True)
if showsize:
print() # Skip to the next line
current_download_size = [0]
GoogleDriveDownloader._save_response_content(response, dest_path, showsize, current_download_size)
print('Done.')
if unzip:
try:
print('Unzipping...', end='')
stdout.flush()
with zipfile.ZipFile(dest_path, 'r') as z:
z.extractall(destination_directory)
print('Done.')
except zipfile.BadZipfile:
warnings.warn('Ignoring `unzip` since "{}" does not look like a valid zip file'.format(file_id)) | [
"def",
"download_file_from_google_drive",
"(",
"file_id",
",",
"dest_path",
",",
"overwrite",
"=",
"False",
",",
"unzip",
"=",
"False",
",",
"showsize",
"=",
"False",
")",
":",
"destination_directory",
"=",
"dirname",
"(",
"dest_path",
")",
"if",
"not",
"exist... | Downloads a shared file from google drive into a given folder.
Optionally unzips it.
Parameters
----------
file_id: str
the file identifier.
You can obtain it from the sharable link.
dest_path: str
the destination where to save the downloaded file.
Must be a path (for example: './downloaded_file.txt')
overwrite: bool
optional, if True forces re-download and overwrite.
unzip: bool
optional, if True unzips a file.
If the file is not a zip file, ignores it.
showsize: bool
optional, if True print the current download size.
Returns
-------
None | [
"Downloads",
"a",
"shared",
"file",
"from",
"google",
"drive",
"into",
"a",
"given",
"folder",
".",
"Optionally",
"unzips",
"it",
"."
] | be1aba9e2e43b2375475f19d8214ca50a8621bd6 | https://github.com/ndrplz/google-drive-downloader/blob/be1aba9e2e43b2375475f19d8214ca50a8621bd6/google_drive_downloader/google_drive_downloader.py#L20-L78 | train | 23,153 |
python-hyper/wsproto | example/synchronous_server.py | handle_connection | def handle_connection(stream):
'''
Handle a connection.
The server operates a request/response cycle, so it performs a synchronous
loop:
1) Read data from network into wsproto
2) Get next wsproto event
3) Handle event
4) Send data from wsproto to network
:param stream: a socket stream
'''
ws = WSConnection(ConnectionType.SERVER)
# events is a generator that yields websocket event objects. Usually you
# would say `for event in ws.events()`, but the synchronous nature of this
# server requires us to use next(event) instead so that we can interleave
# the network I/O.
events = ws.events()
running = True
while running:
# 1) Read data from network
in_data = stream.recv(RECEIVE_BYTES)
print('Received {} bytes'.format(len(in_data)))
ws.receive_data(in_data)
# 2) Get next wsproto event
try:
event = next(events)
except StopIteration:
print('Client connection dropped unexpectedly')
return
# 3) Handle event
if isinstance(event, Request):
# Negotiate new WebSocket connection
print('Accepting WebSocket upgrade')
out_data = ws.send(AcceptConnection())
elif isinstance(event, CloseConnection):
# Print log message and break out
print('Connection closed: code={}/{} reason={}'.format(
event.code.value, event.code.name, event.reason))
out_data = ws.send(event.response())
running = False
elif isinstance(event, TextMessage):
# Reverse text and send it back to wsproto
print('Received request and sending response')
out_data = ws.send(Message(data=event.data[::-1]))
elif isinstance(event, Ping):
# wsproto handles ping events for you by placing a pong frame in
# the outgoing buffer. You should not call pong() unless you want to
# send an unsolicited pong frame.
print('Received ping and sending pong')
out_data = ws.send(event.response())
else:
print('Unknown event: {!r}'.format(event))
# 4) Send data from wsproto to network
print('Sending {} bytes'.format(len(out_data)))
stream.send(out_data) | python | def handle_connection(stream):
'''
Handle a connection.
The server operates a request/response cycle, so it performs a synchronous
loop:
1) Read data from network into wsproto
2) Get next wsproto event
3) Handle event
4) Send data from wsproto to network
:param stream: a socket stream
'''
ws = WSConnection(ConnectionType.SERVER)
# events is a generator that yields websocket event objects. Usually you
# would say `for event in ws.events()`, but the synchronous nature of this
# server requires us to use next(event) instead so that we can interleave
# the network I/O.
events = ws.events()
running = True
while running:
# 1) Read data from network
in_data = stream.recv(RECEIVE_BYTES)
print('Received {} bytes'.format(len(in_data)))
ws.receive_data(in_data)
# 2) Get next wsproto event
try:
event = next(events)
except StopIteration:
print('Client connection dropped unexpectedly')
return
# 3) Handle event
if isinstance(event, Request):
# Negotiate new WebSocket connection
print('Accepting WebSocket upgrade')
out_data = ws.send(AcceptConnection())
elif isinstance(event, CloseConnection):
# Print log message and break out
print('Connection closed: code={}/{} reason={}'.format(
event.code.value, event.code.name, event.reason))
out_data = ws.send(event.response())
running = False
elif isinstance(event, TextMessage):
# Reverse text and send it back to wsproto
print('Received request and sending response')
out_data = ws.send(Message(data=event.data[::-1]))
elif isinstance(event, Ping):
# wsproto handles ping events for you by placing a pong frame in
# the outgoing buffer. You should not call pong() unless you want to
# send an unsolicited pong frame.
print('Received ping and sending pong')
out_data = ws.send(event.response())
else:
print('Unknown event: {!r}'.format(event))
# 4) Send data from wsproto to network
print('Sending {} bytes'.format(len(out_data)))
stream.send(out_data) | [
"def",
"handle_connection",
"(",
"stream",
")",
":",
"ws",
"=",
"WSConnection",
"(",
"ConnectionType",
".",
"SERVER",
")",
"# events is a generator that yields websocket event objects. Usually you",
"# would say `for event in ws.events()`, but the synchronous nature of this",
"# serv... | Handle a connection.
The server operates a request/response cycle, so it performs a synchronous
loop:
1) Read data from network into wsproto
2) Get next wsproto event
3) Handle event
4) Send data from wsproto to network
:param stream: a socket stream | [
"Handle",
"a",
"connection",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/example/synchronous_server.py#L44-L106 | train | 23,154 |
python-hyper/wsproto | wsproto/connection.py | Connection.receive_data | def receive_data(self, data):
# type: (bytes) -> None
"""
Pass some received data to the connection for handling.
A list of events that the remote peer triggered by sending this data can
be retrieved with :meth:`~wsproto.connection.Connection.events`.
:param data: The data received from the remote peer on the network.
:type data: ``bytes``
"""
if data is None:
# "If _The WebSocket Connection is Closed_ and no Close control
# frame was received by the endpoint (such as could occur if the
# underlying transport connection is lost), _The WebSocket
# Connection Close Code_ is considered to be 1006."
self._events.append(CloseConnection(code=CloseReason.ABNORMAL_CLOSURE))
self._state = ConnectionState.CLOSED
return
if self.state in (ConnectionState.OPEN, ConnectionState.LOCAL_CLOSING):
self._proto.receive_bytes(data)
elif self.state is ConnectionState.CLOSED:
raise LocalProtocolError("Connection already closed.") | python | def receive_data(self, data):
# type: (bytes) -> None
"""
Pass some received data to the connection for handling.
A list of events that the remote peer triggered by sending this data can
be retrieved with :meth:`~wsproto.connection.Connection.events`.
:param data: The data received from the remote peer on the network.
:type data: ``bytes``
"""
if data is None:
# "If _The WebSocket Connection is Closed_ and no Close control
# frame was received by the endpoint (such as could occur if the
# underlying transport connection is lost), _The WebSocket
# Connection Close Code_ is considered to be 1006."
self._events.append(CloseConnection(code=CloseReason.ABNORMAL_CLOSURE))
self._state = ConnectionState.CLOSED
return
if self.state in (ConnectionState.OPEN, ConnectionState.LOCAL_CLOSING):
self._proto.receive_bytes(data)
elif self.state is ConnectionState.CLOSED:
raise LocalProtocolError("Connection already closed.") | [
"def",
"receive_data",
"(",
"self",
",",
"data",
")",
":",
"# type: (bytes) -> None",
"if",
"data",
"is",
"None",
":",
"# \"If _The WebSocket Connection is Closed_ and no Close control",
"# frame was received by the endpoint (such as could occur if the",
"# underlying transport conne... | Pass some received data to the connection for handling.
A list of events that the remote peer triggered by sending this data can
be retrieved with :meth:`~wsproto.connection.Connection.events`.
:param data: The data received from the remote peer on the network.
:type data: ``bytes`` | [
"Pass",
"some",
"received",
"data",
"to",
"the",
"connection",
"for",
"handling",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/wsproto/connection.py#L92-L116 | train | 23,155 |
python-hyper/wsproto | wsproto/connection.py | Connection.events | def events(self):
# type: () -> Generator[Event, None, None]
"""
Return a generator that provides any events that have been generated
by protocol activity.
:returns: generator of :class:`Event <wsproto.events.Event>` subclasses
"""
while self._events:
yield self._events.popleft()
try:
for frame in self._proto.received_frames():
if frame.opcode is Opcode.PING:
assert frame.frame_finished and frame.message_finished
yield Ping(payload=frame.payload)
elif frame.opcode is Opcode.PONG:
assert frame.frame_finished and frame.message_finished
yield Pong(payload=frame.payload)
elif frame.opcode is Opcode.CLOSE:
code, reason = frame.payload
if self.state is ConnectionState.LOCAL_CLOSING:
self._state = ConnectionState.CLOSED
else:
self._state = ConnectionState.REMOTE_CLOSING
yield CloseConnection(code=code, reason=reason)
elif frame.opcode is Opcode.TEXT:
yield TextMessage(
data=frame.payload,
frame_finished=frame.frame_finished,
message_finished=frame.message_finished,
)
elif frame.opcode is Opcode.BINARY:
yield BytesMessage(
data=frame.payload,
frame_finished=frame.frame_finished,
message_finished=frame.message_finished,
)
except ParseFailed as exc:
yield CloseConnection(code=exc.code, reason=str(exc)) | python | def events(self):
# type: () -> Generator[Event, None, None]
"""
Return a generator that provides any events that have been generated
by protocol activity.
:returns: generator of :class:`Event <wsproto.events.Event>` subclasses
"""
while self._events:
yield self._events.popleft()
try:
for frame in self._proto.received_frames():
if frame.opcode is Opcode.PING:
assert frame.frame_finished and frame.message_finished
yield Ping(payload=frame.payload)
elif frame.opcode is Opcode.PONG:
assert frame.frame_finished and frame.message_finished
yield Pong(payload=frame.payload)
elif frame.opcode is Opcode.CLOSE:
code, reason = frame.payload
if self.state is ConnectionState.LOCAL_CLOSING:
self._state = ConnectionState.CLOSED
else:
self._state = ConnectionState.REMOTE_CLOSING
yield CloseConnection(code=code, reason=reason)
elif frame.opcode is Opcode.TEXT:
yield TextMessage(
data=frame.payload,
frame_finished=frame.frame_finished,
message_finished=frame.message_finished,
)
elif frame.opcode is Opcode.BINARY:
yield BytesMessage(
data=frame.payload,
frame_finished=frame.frame_finished,
message_finished=frame.message_finished,
)
except ParseFailed as exc:
yield CloseConnection(code=exc.code, reason=str(exc)) | [
"def",
"events",
"(",
"self",
")",
":",
"# type: () -> Generator[Event, None, None]",
"while",
"self",
".",
"_events",
":",
"yield",
"self",
".",
"_events",
".",
"popleft",
"(",
")",
"try",
":",
"for",
"frame",
"in",
"self",
".",
"_proto",
".",
"received_fra... | Return a generator that provides any events that have been generated
by protocol activity.
:returns: generator of :class:`Event <wsproto.events.Event>` subclasses | [
"Return",
"a",
"generator",
"that",
"provides",
"any",
"events",
"that",
"have",
"been",
"generated",
"by",
"protocol",
"activity",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/wsproto/connection.py#L118-L161 | train | 23,156 |
python-hyper/wsproto | wsproto/handshake.py | server_extensions_handshake | def server_extensions_handshake(requested, supported):
# type: (List[str], List[Extension]) -> Optional[bytes]
"""Agree on the extensions to use returning an appropriate header value.
This returns None if there are no agreed extensions
"""
accepts = {}
for offer in requested:
name = offer.split(";", 1)[0].strip()
for extension in supported:
if extension.name == name:
accept = extension.accept(offer)
if accept is True:
accepts[extension.name] = True
elif accept is not False and accept is not None:
accepts[extension.name] = accept.encode("ascii")
if accepts:
extensions = []
for name, params in accepts.items():
if params is True:
extensions.append(name.encode("ascii"))
else:
# py34 annoyance: doesn't support bytestring formatting
params = params.decode("ascii")
if params == "":
extensions.append(("%s" % (name)).encode("ascii"))
else:
extensions.append(("%s; %s" % (name, params)).encode("ascii"))
return b", ".join(extensions)
return None | python | def server_extensions_handshake(requested, supported):
# type: (List[str], List[Extension]) -> Optional[bytes]
"""Agree on the extensions to use returning an appropriate header value.
This returns None if there are no agreed extensions
"""
accepts = {}
for offer in requested:
name = offer.split(";", 1)[0].strip()
for extension in supported:
if extension.name == name:
accept = extension.accept(offer)
if accept is True:
accepts[extension.name] = True
elif accept is not False and accept is not None:
accepts[extension.name] = accept.encode("ascii")
if accepts:
extensions = []
for name, params in accepts.items():
if params is True:
extensions.append(name.encode("ascii"))
else:
# py34 annoyance: doesn't support bytestring formatting
params = params.decode("ascii")
if params == "":
extensions.append(("%s" % (name)).encode("ascii"))
else:
extensions.append(("%s; %s" % (name, params)).encode("ascii"))
return b", ".join(extensions)
return None | [
"def",
"server_extensions_handshake",
"(",
"requested",
",",
"supported",
")",
":",
"# type: (List[str], List[Extension]) -> Optional[bytes]",
"accepts",
"=",
"{",
"}",
"for",
"offer",
"in",
"requested",
":",
"name",
"=",
"offer",
".",
"split",
"(",
"\";\"",
",",
... | Agree on the extensions to use returning an appropriate header value.
This returns None if there are no agreed extensions | [
"Agree",
"on",
"the",
"extensions",
"to",
"use",
"returning",
"an",
"appropriate",
"header",
"value",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/wsproto/handshake.py#L411-L442 | train | 23,157 |
python-hyper/wsproto | wsproto/handshake.py | H11Handshake.initiate_upgrade_connection | def initiate_upgrade_connection(self, headers, path):
# type: (List[Tuple[bytes, bytes]], str) -> None
"""Initiate an upgrade connection.
This should be used if the request has already be received and
parsed.
"""
if self.client:
raise LocalProtocolError(
"Cannot initiate an upgrade connection when acting as the client"
)
upgrade_request = h11.Request(method=b"GET", target=path, headers=headers)
h11_client = h11.Connection(h11.CLIENT)
self.receive_data(h11_client.send(upgrade_request)) | python | def initiate_upgrade_connection(self, headers, path):
# type: (List[Tuple[bytes, bytes]], str) -> None
"""Initiate an upgrade connection.
This should be used if the request has already be received and
parsed.
"""
if self.client:
raise LocalProtocolError(
"Cannot initiate an upgrade connection when acting as the client"
)
upgrade_request = h11.Request(method=b"GET", target=path, headers=headers)
h11_client = h11.Connection(h11.CLIENT)
self.receive_data(h11_client.send(upgrade_request)) | [
"def",
"initiate_upgrade_connection",
"(",
"self",
",",
"headers",
",",
"path",
")",
":",
"# type: (List[Tuple[bytes, bytes]], str) -> None",
"if",
"self",
".",
"client",
":",
"raise",
"LocalProtocolError",
"(",
"\"Cannot initiate an upgrade connection when acting as the client... | Initiate an upgrade connection.
This should be used if the request has already be received and
parsed. | [
"Initiate",
"an",
"upgrade",
"connection",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/wsproto/handshake.py#L61-L75 | train | 23,158 |
python-hyper/wsproto | wsproto/handshake.py | H11Handshake.send | def send(self, event):
# type(Event) -> bytes
"""Send an event to the remote.
This will return the bytes to send based on the event or raise
a LocalProtocolError if the event is not valid given the
state.
"""
data = b""
if isinstance(event, Request):
data += self._initiate_connection(event)
elif isinstance(event, AcceptConnection):
data += self._accept(event)
elif isinstance(event, RejectConnection):
data += self._reject(event)
elif isinstance(event, RejectData):
data += self._send_reject_data(event)
else:
raise LocalProtocolError(
"Event {} cannot be sent during the handshake".format(event)
)
return data | python | def send(self, event):
# type(Event) -> bytes
"""Send an event to the remote.
This will return the bytes to send based on the event or raise
a LocalProtocolError if the event is not valid given the
state.
"""
data = b""
if isinstance(event, Request):
data += self._initiate_connection(event)
elif isinstance(event, AcceptConnection):
data += self._accept(event)
elif isinstance(event, RejectConnection):
data += self._reject(event)
elif isinstance(event, RejectData):
data += self._send_reject_data(event)
else:
raise LocalProtocolError(
"Event {} cannot be sent during the handshake".format(event)
)
return data | [
"def",
"send",
"(",
"self",
",",
"event",
")",
":",
"# type(Event) -> bytes",
"data",
"=",
"b\"\"",
"if",
"isinstance",
"(",
"event",
",",
"Request",
")",
":",
"data",
"+=",
"self",
".",
"_initiate_connection",
"(",
"event",
")",
"elif",
"isinstance",
"(",... | Send an event to the remote.
This will return the bytes to send based on the event or raise
a LocalProtocolError if the event is not valid given the
state. | [
"Send",
"an",
"event",
"to",
"the",
"remote",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/wsproto/handshake.py#L77-L99 | train | 23,159 |
python-hyper/wsproto | wsproto/handshake.py | H11Handshake.receive_data | def receive_data(self, data):
# type: (bytes) -> None
"""Receive data from the remote.
A list of events that the remote peer triggered by sending
this data can be retrieved with :meth:`events`.
"""
self._h11_connection.receive_data(data)
while True:
try:
event = self._h11_connection.next_event()
except h11.RemoteProtocolError:
raise RemoteProtocolError(
"Bad HTTP message", event_hint=RejectConnection()
)
if (
isinstance(event, h11.ConnectionClosed)
or event is h11.NEED_DATA
or event is h11.PAUSED
):
break
if self.client:
if isinstance(event, h11.InformationalResponse):
if event.status_code == 101:
self._events.append(self._establish_client_connection(event))
else:
self._events.append(
RejectConnection(
headers=event.headers,
status_code=event.status_code,
has_body=False,
)
)
self._state = ConnectionState.CLOSED
elif isinstance(event, h11.Response):
self._state = ConnectionState.REJECTING
self._events.append(
RejectConnection(
headers=event.headers,
status_code=event.status_code,
has_body=True,
)
)
elif isinstance(event, h11.Data):
self._events.append(
RejectData(data=event.data, body_finished=False)
)
elif isinstance(event, h11.EndOfMessage):
self._events.append(RejectData(data=b"", body_finished=True))
self._state = ConnectionState.CLOSED
else:
if isinstance(event, h11.Request):
self._events.append(self._process_connection_request(event)) | python | def receive_data(self, data):
# type: (bytes) -> None
"""Receive data from the remote.
A list of events that the remote peer triggered by sending
this data can be retrieved with :meth:`events`.
"""
self._h11_connection.receive_data(data)
while True:
try:
event = self._h11_connection.next_event()
except h11.RemoteProtocolError:
raise RemoteProtocolError(
"Bad HTTP message", event_hint=RejectConnection()
)
if (
isinstance(event, h11.ConnectionClosed)
or event is h11.NEED_DATA
or event is h11.PAUSED
):
break
if self.client:
if isinstance(event, h11.InformationalResponse):
if event.status_code == 101:
self._events.append(self._establish_client_connection(event))
else:
self._events.append(
RejectConnection(
headers=event.headers,
status_code=event.status_code,
has_body=False,
)
)
self._state = ConnectionState.CLOSED
elif isinstance(event, h11.Response):
self._state = ConnectionState.REJECTING
self._events.append(
RejectConnection(
headers=event.headers,
status_code=event.status_code,
has_body=True,
)
)
elif isinstance(event, h11.Data):
self._events.append(
RejectData(data=event.data, body_finished=False)
)
elif isinstance(event, h11.EndOfMessage):
self._events.append(RejectData(data=b"", body_finished=True))
self._state = ConnectionState.CLOSED
else:
if isinstance(event, h11.Request):
self._events.append(self._process_connection_request(event)) | [
"def",
"receive_data",
"(",
"self",
",",
"data",
")",
":",
"# type: (bytes) -> None",
"self",
".",
"_h11_connection",
".",
"receive_data",
"(",
"data",
")",
"while",
"True",
":",
"try",
":",
"event",
"=",
"self",
".",
"_h11_connection",
".",
"next_event",
"(... | Receive data from the remote.
A list of events that the remote peer triggered by sending
this data can be retrieved with :meth:`events`. | [
"Receive",
"data",
"from",
"the",
"remote",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/wsproto/handshake.py#L101-L155 | train | 23,160 |
python-hyper/wsproto | example/synchronous_client.py | net_send | def net_send(out_data, conn):
''' Write pending data from websocket to network. '''
print('Sending {} bytes'.format(len(out_data)))
conn.send(out_data) | python | def net_send(out_data, conn):
''' Write pending data from websocket to network. '''
print('Sending {} bytes'.format(len(out_data)))
conn.send(out_data) | [
"def",
"net_send",
"(",
"out_data",
",",
"conn",
")",
":",
"print",
"(",
"'Sending {} bytes'",
".",
"format",
"(",
"len",
"(",
"out_data",
")",
")",
")",
"conn",
".",
"send",
"(",
"out_data",
")"
] | Write pending data from websocket to network. | [
"Write",
"pending",
"data",
"from",
"websocket",
"to",
"network",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/example/synchronous_client.py#L106-L109 | train | 23,161 |
python-hyper/wsproto | example/synchronous_client.py | net_recv | def net_recv(ws, conn):
''' Read pending data from network into websocket. '''
in_data = conn.recv(RECEIVE_BYTES)
if not in_data:
# A receive of zero bytes indicates the TCP socket has been closed. We
# need to pass None to wsproto to update its internal state.
print('Received 0 bytes (connection closed)')
ws.receive_data(None)
else:
print('Received {} bytes'.format(len(in_data)))
ws.receive_data(in_data) | python | def net_recv(ws, conn):
''' Read pending data from network into websocket. '''
in_data = conn.recv(RECEIVE_BYTES)
if not in_data:
# A receive of zero bytes indicates the TCP socket has been closed. We
# need to pass None to wsproto to update its internal state.
print('Received 0 bytes (connection closed)')
ws.receive_data(None)
else:
print('Received {} bytes'.format(len(in_data)))
ws.receive_data(in_data) | [
"def",
"net_recv",
"(",
"ws",
",",
"conn",
")",
":",
"in_data",
"=",
"conn",
".",
"recv",
"(",
"RECEIVE_BYTES",
")",
"if",
"not",
"in_data",
":",
"# A receive of zero bytes indicates the TCP socket has been closed. We",
"# need to pass None to wsproto to update its internal... | Read pending data from network into websocket. | [
"Read",
"pending",
"data",
"from",
"network",
"into",
"websocket",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/example/synchronous_client.py#L112-L122 | train | 23,162 |
ffalcinelli/pydivert | pydivert/windivert.py | WinDivert.check_filter | def check_filter(filter, layer=Layer.NETWORK):
"""
Checks if the given packet filter string is valid with respect to the filter language.
The remapped function is WinDivertHelperCheckFilter::
BOOL WinDivertHelperCheckFilter(
__in const char *filter,
__in WINDIVERT_LAYER layer,
__out_opt const char **errorStr,
__out_opt UINT *errorPos
);
See: https://reqrypt.org/windivert-doc.html#divert_helper_check_filter
:return: A tuple (res, pos, msg) with check result in 'res' human readable description of the error in 'msg' and the error's position in 'pos'.
"""
res, pos, msg = False, c_uint(), c_char_p()
try:
res = windivert_dll.WinDivertHelperCheckFilter(filter.encode(), layer, byref(msg), byref(pos))
except OSError:
pass
return res, pos.value, msg.value.decode() | python | def check_filter(filter, layer=Layer.NETWORK):
"""
Checks if the given packet filter string is valid with respect to the filter language.
The remapped function is WinDivertHelperCheckFilter::
BOOL WinDivertHelperCheckFilter(
__in const char *filter,
__in WINDIVERT_LAYER layer,
__out_opt const char **errorStr,
__out_opt UINT *errorPos
);
See: https://reqrypt.org/windivert-doc.html#divert_helper_check_filter
:return: A tuple (res, pos, msg) with check result in 'res' human readable description of the error in 'msg' and the error's position in 'pos'.
"""
res, pos, msg = False, c_uint(), c_char_p()
try:
res = windivert_dll.WinDivertHelperCheckFilter(filter.encode(), layer, byref(msg), byref(pos))
except OSError:
pass
return res, pos.value, msg.value.decode() | [
"def",
"check_filter",
"(",
"filter",
",",
"layer",
"=",
"Layer",
".",
"NETWORK",
")",
":",
"res",
",",
"pos",
",",
"msg",
"=",
"False",
",",
"c_uint",
"(",
")",
",",
"c_char_p",
"(",
")",
"try",
":",
"res",
"=",
"windivert_dll",
".",
"WinDivertHelpe... | Checks if the given packet filter string is valid with respect to the filter language.
The remapped function is WinDivertHelperCheckFilter::
BOOL WinDivertHelperCheckFilter(
__in const char *filter,
__in WINDIVERT_LAYER layer,
__out_opt const char **errorStr,
__out_opt UINT *errorPos
);
See: https://reqrypt.org/windivert-doc.html#divert_helper_check_filter
:return: A tuple (res, pos, msg) with check result in 'res' human readable description of the error in 'msg' and the error's position in 'pos'. | [
"Checks",
"if",
"the",
"given",
"packet",
"filter",
"string",
"is",
"valid",
"with",
"respect",
"to",
"the",
"filter",
"language",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert.py#L102-L124 | train | 23,163 |
ffalcinelli/pydivert | pydivert/windivert.py | WinDivert.recv | def recv(self, bufsize=DEFAULT_PACKET_BUFFER_SIZE):
"""
Receives a diverted packet that matched the filter.
The remapped function is WinDivertRecv::
BOOL WinDivertRecv(
__in HANDLE handle,
__out PVOID pPacket,
__in UINT packetLen,
__out_opt PWINDIVERT_ADDRESS pAddr,
__out_opt UINT *recvLen
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_recv
:return: The return value is a `pydivert.Packet`.
"""
if self._handle is None:
raise RuntimeError("WinDivert handle is not open")
packet = bytearray(bufsize)
packet_ = (c_char * bufsize).from_buffer(packet)
address = windivert_dll.WinDivertAddress()
recv_len = c_uint(0)
windivert_dll.WinDivertRecv(self._handle, packet_, bufsize, byref(address), byref(recv_len))
return Packet(
memoryview(packet)[:recv_len.value],
(address.IfIdx, address.SubIfIdx),
Direction(address.Direction)
) | python | def recv(self, bufsize=DEFAULT_PACKET_BUFFER_SIZE):
"""
Receives a diverted packet that matched the filter.
The remapped function is WinDivertRecv::
BOOL WinDivertRecv(
__in HANDLE handle,
__out PVOID pPacket,
__in UINT packetLen,
__out_opt PWINDIVERT_ADDRESS pAddr,
__out_opt UINT *recvLen
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_recv
:return: The return value is a `pydivert.Packet`.
"""
if self._handle is None:
raise RuntimeError("WinDivert handle is not open")
packet = bytearray(bufsize)
packet_ = (c_char * bufsize).from_buffer(packet)
address = windivert_dll.WinDivertAddress()
recv_len = c_uint(0)
windivert_dll.WinDivertRecv(self._handle, packet_, bufsize, byref(address), byref(recv_len))
return Packet(
memoryview(packet)[:recv_len.value],
(address.IfIdx, address.SubIfIdx),
Direction(address.Direction)
) | [
"def",
"recv",
"(",
"self",
",",
"bufsize",
"=",
"DEFAULT_PACKET_BUFFER_SIZE",
")",
":",
"if",
"self",
".",
"_handle",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"WinDivert handle is not open\"",
")",
"packet",
"=",
"bytearray",
"(",
"bufsize",
")",
"p... | Receives a diverted packet that matched the filter.
The remapped function is WinDivertRecv::
BOOL WinDivertRecv(
__in HANDLE handle,
__out PVOID pPacket,
__in UINT packetLen,
__out_opt PWINDIVERT_ADDRESS pAddr,
__out_opt UINT *recvLen
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_recv
:return: The return value is a `pydivert.Packet`. | [
"Receives",
"a",
"diverted",
"packet",
"that",
"matched",
"the",
"filter",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert.py#L172-L202 | train | 23,164 |
ffalcinelli/pydivert | pydivert/windivert.py | WinDivert.send | def send(self, packet, recalculate_checksum=True):
"""
Injects a packet into the network stack.
Recalculates the checksum before sending unless recalculate_checksum=False is passed.
The injected packet may be one received from recv(), or a modified version, or a completely new packet.
Injected packets can be captured and diverted again by other WinDivert handles with lower priorities.
The remapped function is WinDivertSend::
BOOL WinDivertSend(
__in HANDLE handle,
__in PVOID pPacket,
__in UINT packetLen,
__in PWINDIVERT_ADDRESS pAddr,
__out_opt UINT *sendLen
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_send
:return: The return value is the number of bytes actually sent.
"""
if recalculate_checksum:
packet.recalculate_checksums()
send_len = c_uint(0)
if PY2:
# .from_buffer(memoryview) does not work on PY2
buff = bytearray(packet.raw)
else:
buff = packet.raw
buff = (c_char * len(packet.raw)).from_buffer(buff)
windivert_dll.WinDivertSend(self._handle, buff, len(packet.raw), byref(packet.wd_addr),
byref(send_len))
return send_len | python | def send(self, packet, recalculate_checksum=True):
"""
Injects a packet into the network stack.
Recalculates the checksum before sending unless recalculate_checksum=False is passed.
The injected packet may be one received from recv(), or a modified version, or a completely new packet.
Injected packets can be captured and diverted again by other WinDivert handles with lower priorities.
The remapped function is WinDivertSend::
BOOL WinDivertSend(
__in HANDLE handle,
__in PVOID pPacket,
__in UINT packetLen,
__in PWINDIVERT_ADDRESS pAddr,
__out_opt UINT *sendLen
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_send
:return: The return value is the number of bytes actually sent.
"""
if recalculate_checksum:
packet.recalculate_checksums()
send_len = c_uint(0)
if PY2:
# .from_buffer(memoryview) does not work on PY2
buff = bytearray(packet.raw)
else:
buff = packet.raw
buff = (c_char * len(packet.raw)).from_buffer(buff)
windivert_dll.WinDivertSend(self._handle, buff, len(packet.raw), byref(packet.wd_addr),
byref(send_len))
return send_len | [
"def",
"send",
"(",
"self",
",",
"packet",
",",
"recalculate_checksum",
"=",
"True",
")",
":",
"if",
"recalculate_checksum",
":",
"packet",
".",
"recalculate_checksums",
"(",
")",
"send_len",
"=",
"c_uint",
"(",
"0",
")",
"if",
"PY2",
":",
"# .from_buffer(me... | Injects a packet into the network stack.
Recalculates the checksum before sending unless recalculate_checksum=False is passed.
The injected packet may be one received from recv(), or a modified version, or a completely new packet.
Injected packets can be captured and diverted again by other WinDivert handles with lower priorities.
The remapped function is WinDivertSend::
BOOL WinDivertSend(
__in HANDLE handle,
__in PVOID pPacket,
__in UINT packetLen,
__in PWINDIVERT_ADDRESS pAddr,
__out_opt UINT *sendLen
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_send
:return: The return value is the number of bytes actually sent. | [
"Injects",
"a",
"packet",
"into",
"the",
"network",
"stack",
".",
"Recalculates",
"the",
"checksum",
"before",
"sending",
"unless",
"recalculate_checksum",
"=",
"False",
"is",
"passed",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert.py#L204-L238 | train | 23,165 |
ffalcinelli/pydivert | pydivert/windivert.py | WinDivert.get_param | def get_param(self, name):
"""
Get a WinDivert parameter. See pydivert.Param for the list of parameters.
The remapped function is WinDivertGetParam::
BOOL WinDivertGetParam(
__in HANDLE handle,
__in WINDIVERT_PARAM param,
__out UINT64 *pValue
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_get_param
:return: The parameter value.
"""
value = c_uint64(0)
windivert_dll.WinDivertGetParam(self._handle, name, byref(value))
return value.value | python | def get_param(self, name):
"""
Get a WinDivert parameter. See pydivert.Param for the list of parameters.
The remapped function is WinDivertGetParam::
BOOL WinDivertGetParam(
__in HANDLE handle,
__in WINDIVERT_PARAM param,
__out UINT64 *pValue
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_get_param
:return: The parameter value.
"""
value = c_uint64(0)
windivert_dll.WinDivertGetParam(self._handle, name, byref(value))
return value.value | [
"def",
"get_param",
"(",
"self",
",",
"name",
")",
":",
"value",
"=",
"c_uint64",
"(",
"0",
")",
"windivert_dll",
".",
"WinDivertGetParam",
"(",
"self",
".",
"_handle",
",",
"name",
",",
"byref",
"(",
"value",
")",
")",
"return",
"value",
".",
"value"
... | Get a WinDivert parameter. See pydivert.Param for the list of parameters.
The remapped function is WinDivertGetParam::
BOOL WinDivertGetParam(
__in HANDLE handle,
__in WINDIVERT_PARAM param,
__out UINT64 *pValue
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_get_param
:return: The parameter value. | [
"Get",
"a",
"WinDivert",
"parameter",
".",
"See",
"pydivert",
".",
"Param",
"for",
"the",
"list",
"of",
"parameters",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert.py#L240-L258 | train | 23,166 |
ffalcinelli/pydivert | pydivert/windivert.py | WinDivert.set_param | def set_param(self, name, value):
"""
Set a WinDivert parameter. See pydivert.Param for the list of parameters.
The remapped function is DivertSetParam::
BOOL WinDivertSetParam(
__in HANDLE handle,
__in WINDIVERT_PARAM param,
__in UINT64 value
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_set_param
"""
return windivert_dll.WinDivertSetParam(self._handle, name, value) | python | def set_param(self, name, value):
"""
Set a WinDivert parameter. See pydivert.Param for the list of parameters.
The remapped function is DivertSetParam::
BOOL WinDivertSetParam(
__in HANDLE handle,
__in WINDIVERT_PARAM param,
__in UINT64 value
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_set_param
"""
return windivert_dll.WinDivertSetParam(self._handle, name, value) | [
"def",
"set_param",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"return",
"windivert_dll",
".",
"WinDivertSetParam",
"(",
"self",
".",
"_handle",
",",
"name",
",",
"value",
")"
] | Set a WinDivert parameter. See pydivert.Param for the list of parameters.
The remapped function is DivertSetParam::
BOOL WinDivertSetParam(
__in HANDLE handle,
__in WINDIVERT_PARAM param,
__in UINT64 value
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_set_param | [
"Set",
"a",
"WinDivert",
"parameter",
".",
"See",
"pydivert",
".",
"Param",
"for",
"the",
"list",
"of",
"parameters",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert.py#L260-L274 | train | 23,167 |
ffalcinelli/pydivert | pydivert/windivert_dll/__init__.py | _init | def _init():
"""
Lazy-load DLL, replace proxy functions with actual ones.
"""
i = instance()
for funcname in WINDIVERT_FUNCTIONS:
func = getattr(i, funcname)
func = raise_on_error(func)
setattr(_module, funcname, func) | python | def _init():
"""
Lazy-load DLL, replace proxy functions with actual ones.
"""
i = instance()
for funcname in WINDIVERT_FUNCTIONS:
func = getattr(i, funcname)
func = raise_on_error(func)
setattr(_module, funcname, func) | [
"def",
"_init",
"(",
")",
":",
"i",
"=",
"instance",
"(",
")",
"for",
"funcname",
"in",
"WINDIVERT_FUNCTIONS",
":",
"func",
"=",
"getattr",
"(",
"i",
",",
"funcname",
")",
"func",
"=",
"raise_on_error",
"(",
"func",
")",
"setattr",
"(",
"_module",
",",... | Lazy-load DLL, replace proxy functions with actual ones. | [
"Lazy",
"-",
"load",
"DLL",
"replace",
"proxy",
"functions",
"with",
"actual",
"ones",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert_dll/__init__.py#L99-L107 | train | 23,168 |
ffalcinelli/pydivert | pydivert/windivert_dll/__init__.py | _mkprox | def _mkprox(funcname):
"""
Make lazy-init proxy function.
"""
def prox(*args, **kwargs):
_init()
return getattr(_module, funcname)(*args, **kwargs)
return prox | python | def _mkprox(funcname):
"""
Make lazy-init proxy function.
"""
def prox(*args, **kwargs):
_init()
return getattr(_module, funcname)(*args, **kwargs)
return prox | [
"def",
"_mkprox",
"(",
"funcname",
")",
":",
"def",
"prox",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_init",
"(",
")",
"return",
"getattr",
"(",
"_module",
",",
"funcname",
")",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return... | Make lazy-init proxy function. | [
"Make",
"lazy",
"-",
"init",
"proxy",
"function",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert_dll/__init__.py#L110-L119 | train | 23,169 |
ffalcinelli/pydivert | pydivert/packet/ip.py | IPHeader.src_addr | def src_addr(self):
"""
The packet source address.
"""
try:
return socket.inet_ntop(self._af, self.raw[self._src_addr].tobytes())
except (ValueError, socket.error):
pass | python | def src_addr(self):
"""
The packet source address.
"""
try:
return socket.inet_ntop(self._af, self.raw[self._src_addr].tobytes())
except (ValueError, socket.error):
pass | [
"def",
"src_addr",
"(",
"self",
")",
":",
"try",
":",
"return",
"socket",
".",
"inet_ntop",
"(",
"self",
".",
"_af",
",",
"self",
".",
"raw",
"[",
"self",
".",
"_src_addr",
"]",
".",
"tobytes",
"(",
")",
")",
"except",
"(",
"ValueError",
",",
"sock... | The packet source address. | [
"The",
"packet",
"source",
"address",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/ip.py#L29-L36 | train | 23,170 |
ffalcinelli/pydivert | pydivert/packet/ip.py | IPHeader.dst_addr | def dst_addr(self):
"""
The packet destination address.
"""
try:
return socket.inet_ntop(self._af, self.raw[self._dst_addr].tobytes())
except (ValueError, socket.error):
pass | python | def dst_addr(self):
"""
The packet destination address.
"""
try:
return socket.inet_ntop(self._af, self.raw[self._dst_addr].tobytes())
except (ValueError, socket.error):
pass | [
"def",
"dst_addr",
"(",
"self",
")",
":",
"try",
":",
"return",
"socket",
".",
"inet_ntop",
"(",
"self",
".",
"_af",
",",
"self",
".",
"raw",
"[",
"self",
".",
"_dst_addr",
"]",
".",
"tobytes",
"(",
")",
")",
"except",
"(",
"ValueError",
",",
"sock... | The packet destination address. | [
"The",
"packet",
"destination",
"address",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/ip.py#L43-L50 | train | 23,171 |
ffalcinelli/pydivert | pydivert/packet/__init__.py | Packet.icmpv4 | def icmpv4(self):
"""
- An ICMPv4Header instance, if the packet is valid ICMPv4.
- None, otherwise.
"""
ipproto, proto_start = self.protocol
if ipproto == Protocol.ICMP:
return ICMPv4Header(self, proto_start) | python | def icmpv4(self):
"""
- An ICMPv4Header instance, if the packet is valid ICMPv4.
- None, otherwise.
"""
ipproto, proto_start = self.protocol
if ipproto == Protocol.ICMP:
return ICMPv4Header(self, proto_start) | [
"def",
"icmpv4",
"(",
"self",
")",
":",
"ipproto",
",",
"proto_start",
"=",
"self",
".",
"protocol",
"if",
"ipproto",
"==",
"Protocol",
".",
"ICMP",
":",
"return",
"ICMPv4Header",
"(",
"self",
",",
"proto_start",
")"
] | - An ICMPv4Header instance, if the packet is valid ICMPv4.
- None, otherwise. | [
"-",
"An",
"ICMPv4Header",
"instance",
"if",
"the",
"packet",
"is",
"valid",
"ICMPv4",
".",
"-",
"None",
"otherwise",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/__init__.py#L176-L183 | train | 23,172 |
ffalcinelli/pydivert | pydivert/packet/__init__.py | Packet.icmpv6 | def icmpv6(self):
"""
- An ICMPv6Header instance, if the packet is valid ICMPv6.
- None, otherwise.
"""
ipproto, proto_start = self.protocol
if ipproto == Protocol.ICMPV6:
return ICMPv6Header(self, proto_start) | python | def icmpv6(self):
"""
- An ICMPv6Header instance, if the packet is valid ICMPv6.
- None, otherwise.
"""
ipproto, proto_start = self.protocol
if ipproto == Protocol.ICMPV6:
return ICMPv6Header(self, proto_start) | [
"def",
"icmpv6",
"(",
"self",
")",
":",
"ipproto",
",",
"proto_start",
"=",
"self",
".",
"protocol",
"if",
"ipproto",
"==",
"Protocol",
".",
"ICMPV6",
":",
"return",
"ICMPv6Header",
"(",
"self",
",",
"proto_start",
")"
] | - An ICMPv6Header instance, if the packet is valid ICMPv6.
- None, otherwise. | [
"-",
"An",
"ICMPv6Header",
"instance",
"if",
"the",
"packet",
"is",
"valid",
"ICMPv6",
".",
"-",
"None",
"otherwise",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/__init__.py#L186-L193 | train | 23,173 |
ffalcinelli/pydivert | pydivert/packet/__init__.py | Packet.tcp | def tcp(self):
"""
- An TCPHeader instance, if the packet is valid TCP.
- None, otherwise.
"""
ipproto, proto_start = self.protocol
if ipproto == Protocol.TCP:
return TCPHeader(self, proto_start) | python | def tcp(self):
"""
- An TCPHeader instance, if the packet is valid TCP.
- None, otherwise.
"""
ipproto, proto_start = self.protocol
if ipproto == Protocol.TCP:
return TCPHeader(self, proto_start) | [
"def",
"tcp",
"(",
"self",
")",
":",
"ipproto",
",",
"proto_start",
"=",
"self",
".",
"protocol",
"if",
"ipproto",
"==",
"Protocol",
".",
"TCP",
":",
"return",
"TCPHeader",
"(",
"self",
",",
"proto_start",
")"
] | - An TCPHeader instance, if the packet is valid TCP.
- None, otherwise. | [
"-",
"An",
"TCPHeader",
"instance",
"if",
"the",
"packet",
"is",
"valid",
"TCP",
".",
"-",
"None",
"otherwise",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/__init__.py#L204-L211 | train | 23,174 |
ffalcinelli/pydivert | pydivert/packet/__init__.py | Packet.udp | def udp(self):
"""
- An TCPHeader instance, if the packet is valid UDP.
- None, otherwise.
"""
ipproto, proto_start = self.protocol
if ipproto == Protocol.UDP:
return UDPHeader(self, proto_start) | python | def udp(self):
"""
- An TCPHeader instance, if the packet is valid UDP.
- None, otherwise.
"""
ipproto, proto_start = self.protocol
if ipproto == Protocol.UDP:
return UDPHeader(self, proto_start) | [
"def",
"udp",
"(",
"self",
")",
":",
"ipproto",
",",
"proto_start",
"=",
"self",
".",
"protocol",
"if",
"ipproto",
"==",
"Protocol",
".",
"UDP",
":",
"return",
"UDPHeader",
"(",
"self",
",",
"proto_start",
")"
] | - An TCPHeader instance, if the packet is valid UDP.
- None, otherwise. | [
"-",
"An",
"TCPHeader",
"instance",
"if",
"the",
"packet",
"is",
"valid",
"UDP",
".",
"-",
"None",
"otherwise",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/__init__.py#L214-L221 | train | 23,175 |
ffalcinelli/pydivert | pydivert/packet/__init__.py | Packet._payload | def _payload(self):
"""header that implements PayloadMixin"""
return self.tcp or self.udp or self.icmpv4 or self.icmpv6 | python | def _payload(self):
"""header that implements PayloadMixin"""
return self.tcp or self.udp or self.icmpv4 or self.icmpv6 | [
"def",
"_payload",
"(",
"self",
")",
":",
"return",
"self",
".",
"tcp",
"or",
"self",
".",
"udp",
"or",
"self",
".",
"icmpv4",
"or",
"self",
".",
"icmpv6"
] | header that implements PayloadMixin | [
"header",
"that",
"implements",
"PayloadMixin"
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/__init__.py#L229-L231 | train | 23,176 |
ffalcinelli/pydivert | pydivert/packet/__init__.py | Packet.matches | def matches(self, filter, layer=Layer.NETWORK):
"""
Evaluates the packet against the given packet filter string.
The remapped function is::
BOOL WinDivertHelperEvalFilter(
__in const char *filter,
__in WINDIVERT_LAYER layer,
__in PVOID pPacket,
__in UINT packetLen,
__in PWINDIVERT_ADDRESS pAddr
);
See: https://reqrypt.org/windivert-doc.html#divert_helper_eval_filter
:param filter: The filter string.
:param layer: The network layer.
:return: True if the packet matches, and False otherwise.
"""
buff, buff_ = self.__to_buffers()
return windivert_dll.WinDivertHelperEvalFilter(filter.encode(), layer, ctypes.byref(buff_), len(self.raw),
ctypes.byref(self.wd_addr)) | python | def matches(self, filter, layer=Layer.NETWORK):
"""
Evaluates the packet against the given packet filter string.
The remapped function is::
BOOL WinDivertHelperEvalFilter(
__in const char *filter,
__in WINDIVERT_LAYER layer,
__in PVOID pPacket,
__in UINT packetLen,
__in PWINDIVERT_ADDRESS pAddr
);
See: https://reqrypt.org/windivert-doc.html#divert_helper_eval_filter
:param filter: The filter string.
:param layer: The network layer.
:return: True if the packet matches, and False otherwise.
"""
buff, buff_ = self.__to_buffers()
return windivert_dll.WinDivertHelperEvalFilter(filter.encode(), layer, ctypes.byref(buff_), len(self.raw),
ctypes.byref(self.wd_addr)) | [
"def",
"matches",
"(",
"self",
",",
"filter",
",",
"layer",
"=",
"Layer",
".",
"NETWORK",
")",
":",
"buff",
",",
"buff_",
"=",
"self",
".",
"__to_buffers",
"(",
")",
"return",
"windivert_dll",
".",
"WinDivertHelperEvalFilter",
"(",
"filter",
".",
"encode",... | Evaluates the packet against the given packet filter string.
The remapped function is::
BOOL WinDivertHelperEvalFilter(
__in const char *filter,
__in WINDIVERT_LAYER layer,
__in PVOID pPacket,
__in UINT packetLen,
__in PWINDIVERT_ADDRESS pAddr
);
See: https://reqrypt.org/windivert-doc.html#divert_helper_eval_filter
:param filter: The filter string.
:param layer: The network layer.
:return: True if the packet matches, and False otherwise. | [
"Evaluates",
"the",
"packet",
"against",
"the",
"given",
"packet",
"filter",
"string",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/__init__.py#L328-L350 | train | 23,177 |
floydhub/floyd-cli | floyd/cli/experiment.py | init | def init(project_name):
"""
Initialize new project at the current path.
After this you can run other FloydHub commands like status and run.
"""
project_obj = ProjectClient().get_by_name(project_name)
if not project_obj:
namespace, name = get_namespace_from_name(project_name)
create_project_base_url = "{}/projects/create".format(floyd.floyd_web_host)
create_project_url = "{}?name={}&namespace={}".format(create_project_base_url, name, namespace)
floyd_logger.info(('Project name does not yet exist on floydhub.com. '
'Create your new project on floydhub.com:\n\t%s'),
create_project_base_url)
webbrowser.open(create_project_url)
name = click.prompt('Press ENTER to use project name "%s" or enter a different name' % project_name, default=project_name, show_default=False)
project_name = name.strip() or project_name
project_obj = ProjectClient().get_by_name(project_name)
if not project_obj:
raise FloydException('Project "%s" does not exist on floydhub.com. Ensure it exists before continuing.' % project_name)
namespace, name = get_namespace_from_name(project_name)
experiment_config = ExperimentConfig(name=name,
namespace=namespace,
family_id=project_obj.id)
ExperimentConfigManager.set_config(experiment_config)
FloydIgnoreManager.init()
yaml_config = read_yaml_config()
if not yaml_config:
copyfile(os.path.join(os.path.dirname(__file__), 'default_floyd.yml'), 'floyd.yml')
floyd_logger.info("Project \"%s\" initialized in current directory", project_name) | python | def init(project_name):
"""
Initialize new project at the current path.
After this you can run other FloydHub commands like status and run.
"""
project_obj = ProjectClient().get_by_name(project_name)
if not project_obj:
namespace, name = get_namespace_from_name(project_name)
create_project_base_url = "{}/projects/create".format(floyd.floyd_web_host)
create_project_url = "{}?name={}&namespace={}".format(create_project_base_url, name, namespace)
floyd_logger.info(('Project name does not yet exist on floydhub.com. '
'Create your new project on floydhub.com:\n\t%s'),
create_project_base_url)
webbrowser.open(create_project_url)
name = click.prompt('Press ENTER to use project name "%s" or enter a different name' % project_name, default=project_name, show_default=False)
project_name = name.strip() or project_name
project_obj = ProjectClient().get_by_name(project_name)
if not project_obj:
raise FloydException('Project "%s" does not exist on floydhub.com. Ensure it exists before continuing.' % project_name)
namespace, name = get_namespace_from_name(project_name)
experiment_config = ExperimentConfig(name=name,
namespace=namespace,
family_id=project_obj.id)
ExperimentConfigManager.set_config(experiment_config)
FloydIgnoreManager.init()
yaml_config = read_yaml_config()
if not yaml_config:
copyfile(os.path.join(os.path.dirname(__file__), 'default_floyd.yml'), 'floyd.yml')
floyd_logger.info("Project \"%s\" initialized in current directory", project_name) | [
"def",
"init",
"(",
"project_name",
")",
":",
"project_obj",
"=",
"ProjectClient",
"(",
")",
".",
"get_by_name",
"(",
"project_name",
")",
"if",
"not",
"project_obj",
":",
"namespace",
",",
"name",
"=",
"get_namespace_from_name",
"(",
"project_name",
")",
"cre... | Initialize new project at the current path.
After this you can run other FloydHub commands like status and run. | [
"Initialize",
"new",
"project",
"at",
"the",
"current",
"path",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L40-L77 | train | 23,178 |
floydhub/floyd-cli | floyd/cli/experiment.py | status | def status(id):
"""
View status of all jobs in a project.
The command also accepts a specific job name.
"""
if id:
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
print_experiments([experiment])
else:
experiments = ExperimentClient().get_all()
print_experiments(experiments) | python | def status(id):
"""
View status of all jobs in a project.
The command also accepts a specific job name.
"""
if id:
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
print_experiments([experiment])
else:
experiments = ExperimentClient().get_all()
print_experiments(experiments) | [
"def",
"status",
"(",
"id",
")",
":",
"if",
"id",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"id",
")",
")",
"except",
"FloydException",
":",
"experiment",
"=",
"ExperimentClient",
"(",
"... | View status of all jobs in a project.
The command also accepts a specific job name. | [
"View",
"status",
"of",
"all",
"jobs",
"in",
"a",
"project",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L82-L97 | train | 23,179 |
floydhub/floyd-cli | floyd/cli/experiment.py | print_experiments | def print_experiments(experiments):
"""
Prints job details in a table. Includes urls and mode parameters
"""
headers = ["JOB NAME", "CREATED", "STATUS", "DURATION(s)", "INSTANCE", "DESCRIPTION", "METRICS"]
expt_list = []
for experiment in experiments:
expt_list.append([normalize_job_name(experiment.name),
experiment.created_pretty, experiment.state,
experiment.duration_rounded, experiment.instance_type_trimmed,
experiment.description, format_metrics(experiment.latest_metrics)])
floyd_logger.info(tabulate(expt_list, headers=headers)) | python | def print_experiments(experiments):
"""
Prints job details in a table. Includes urls and mode parameters
"""
headers = ["JOB NAME", "CREATED", "STATUS", "DURATION(s)", "INSTANCE", "DESCRIPTION", "METRICS"]
expt_list = []
for experiment in experiments:
expt_list.append([normalize_job_name(experiment.name),
experiment.created_pretty, experiment.state,
experiment.duration_rounded, experiment.instance_type_trimmed,
experiment.description, format_metrics(experiment.latest_metrics)])
floyd_logger.info(tabulate(expt_list, headers=headers)) | [
"def",
"print_experiments",
"(",
"experiments",
")",
":",
"headers",
"=",
"[",
"\"JOB NAME\"",
",",
"\"CREATED\"",
",",
"\"STATUS\"",
",",
"\"DURATION(s)\"",
",",
"\"INSTANCE\"",
",",
"\"DESCRIPTION\"",
",",
"\"METRICS\"",
"]",
"expt_list",
"=",
"[",
"]",
"for",... | Prints job details in a table. Includes urls and mode parameters | [
"Prints",
"job",
"details",
"in",
"a",
"table",
".",
"Includes",
"urls",
"and",
"mode",
"parameters"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L100-L111 | train | 23,180 |
floydhub/floyd-cli | floyd/cli/experiment.py | clone | def clone(id, path):
"""
- Download all files from a job
Eg: alice/projects/mnist/1/
Note: This will download the files that were originally uploaded at
the start of the job.
- Download files in a specific path from a job
Specify the path to a directory and download all its files and subdirectories.
Eg: --path models/checkpoint1
"""
try:
experiment = ExperimentClient().get(normalize_job_name(id, use_config=False))
except FloydException:
experiment = ExperimentClient().get(id)
task_instance_id = get_module_task_instance_id(experiment.task_instances)
task_instance = TaskInstanceClient().get(task_instance_id) if task_instance_id else None
if not task_instance:
sys.exit("Cannot clone this version of the job. Try a different version.")
module = ModuleClient().get(task_instance.module_id) if task_instance else None
if path:
# Download a directory from Code
code_url = "{}/api/v1/download/artifacts/code/{}?is_dir=true&path={}".format(floyd.floyd_host,
experiment.id,
path)
else:
# Download the full Code
code_url = "{}/api/v1/resources/{}?content=true&download=true".format(floyd.floyd_host,
module.resource_id)
ExperimentClient().download_tar(url=code_url,
untar=True,
delete_after_untar=True) | python | def clone(id, path):
"""
- Download all files from a job
Eg: alice/projects/mnist/1/
Note: This will download the files that were originally uploaded at
the start of the job.
- Download files in a specific path from a job
Specify the path to a directory and download all its files and subdirectories.
Eg: --path models/checkpoint1
"""
try:
experiment = ExperimentClient().get(normalize_job_name(id, use_config=False))
except FloydException:
experiment = ExperimentClient().get(id)
task_instance_id = get_module_task_instance_id(experiment.task_instances)
task_instance = TaskInstanceClient().get(task_instance_id) if task_instance_id else None
if not task_instance:
sys.exit("Cannot clone this version of the job. Try a different version.")
module = ModuleClient().get(task_instance.module_id) if task_instance else None
if path:
# Download a directory from Code
code_url = "{}/api/v1/download/artifacts/code/{}?is_dir=true&path={}".format(floyd.floyd_host,
experiment.id,
path)
else:
# Download the full Code
code_url = "{}/api/v1/resources/{}?content=true&download=true".format(floyd.floyd_host,
module.resource_id)
ExperimentClient().download_tar(url=code_url,
untar=True,
delete_after_untar=True) | [
"def",
"clone",
"(",
"id",
",",
"path",
")",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"id",
",",
"use_config",
"=",
"False",
")",
")",
"except",
"FloydException",
":",
"experiment",
"="... | - Download all files from a job
Eg: alice/projects/mnist/1/
Note: This will download the files that were originally uploaded at
the start of the job.
- Download files in a specific path from a job
Specify the path to a directory and download all its files and subdirectories.
Eg: --path models/checkpoint1 | [
"-",
"Download",
"all",
"files",
"from",
"a",
"job"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L124-L161 | train | 23,181 |
floydhub/floyd-cli | floyd/cli/experiment.py | info | def info(job_name_or_id):
"""
View detailed information of a job.
"""
try:
experiment = ExperimentClient().get(normalize_job_name(job_name_or_id))
except FloydException:
experiment = ExperimentClient().get(job_name_or_id)
task_instance_id = get_module_task_instance_id(experiment.task_instances)
task_instance = TaskInstanceClient().get(task_instance_id) if task_instance_id else None
normalized_job_name = normalize_job_name(experiment.name)
table = [["Job name", normalized_job_name],
["Created", experiment.created_pretty],
["Status", experiment.state], ["Duration(s)", experiment.duration_rounded],
["Instance", experiment.instance_type_trimmed],
["Description", experiment.description],
["Metrics", format_metrics(experiment.latest_metrics)]]
if task_instance and task_instance.mode in ['jupyter', 'serving']:
table.append(["Mode", task_instance.mode])
table.append(["Url", experiment.service_url])
if experiment.tensorboard_url:
table.append(["TensorBoard", experiment.tensorboard_url])
floyd_logger.info(tabulate(table)) | python | def info(job_name_or_id):
"""
View detailed information of a job.
"""
try:
experiment = ExperimentClient().get(normalize_job_name(job_name_or_id))
except FloydException:
experiment = ExperimentClient().get(job_name_or_id)
task_instance_id = get_module_task_instance_id(experiment.task_instances)
task_instance = TaskInstanceClient().get(task_instance_id) if task_instance_id else None
normalized_job_name = normalize_job_name(experiment.name)
table = [["Job name", normalized_job_name],
["Created", experiment.created_pretty],
["Status", experiment.state], ["Duration(s)", experiment.duration_rounded],
["Instance", experiment.instance_type_trimmed],
["Description", experiment.description],
["Metrics", format_metrics(experiment.latest_metrics)]]
if task_instance and task_instance.mode in ['jupyter', 'serving']:
table.append(["Mode", task_instance.mode])
table.append(["Url", experiment.service_url])
if experiment.tensorboard_url:
table.append(["TensorBoard", experiment.tensorboard_url])
floyd_logger.info(tabulate(table)) | [
"def",
"info",
"(",
"job_name_or_id",
")",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"job_name_or_id",
")",
")",
"except",
"FloydException",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")... | View detailed information of a job. | [
"View",
"detailed",
"information",
"of",
"a",
"job",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L166-L189 | train | 23,182 |
floydhub/floyd-cli | floyd/cli/experiment.py | follow_logs | def follow_logs(instance_log_id, sleep_duration=1):
"""
Follow the logs until Job termination.
"""
cur_idx = 0
job_terminated = False
while not job_terminated:
# Get the logs in a loop and log the new lines
log_file_contents = ResourceClient().get_content(instance_log_id)
print_output = log_file_contents[cur_idx:]
# Get the status of the Job from the current log line
job_terminated = any(terminal_output in print_output for terminal_output in TERMINATION_OUTPUT_LIST)
cur_idx += len(print_output)
sys.stdout.write(print_output)
sleep(sleep_duration) | python | def follow_logs(instance_log_id, sleep_duration=1):
"""
Follow the logs until Job termination.
"""
cur_idx = 0
job_terminated = False
while not job_terminated:
# Get the logs in a loop and log the new lines
log_file_contents = ResourceClient().get_content(instance_log_id)
print_output = log_file_contents[cur_idx:]
# Get the status of the Job from the current log line
job_terminated = any(terminal_output in print_output for terminal_output in TERMINATION_OUTPUT_LIST)
cur_idx += len(print_output)
sys.stdout.write(print_output)
sleep(sleep_duration) | [
"def",
"follow_logs",
"(",
"instance_log_id",
",",
"sleep_duration",
"=",
"1",
")",
":",
"cur_idx",
"=",
"0",
"job_terminated",
"=",
"False",
"while",
"not",
"job_terminated",
":",
"# Get the logs in a loop and log the new lines",
"log_file_contents",
"=",
"ResourceClie... | Follow the logs until Job termination. | [
"Follow",
"the",
"logs",
"until",
"Job",
"termination",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L212-L227 | train | 23,183 |
floydhub/floyd-cli | floyd/cli/experiment.py | logs | def logs(id, url, follow, sleep_duration=1):
"""
View the logs of a job.
To follow along a job in real time, use the --follow flag
"""
instance_log_id = get_log_id(id)
if url:
log_url = "{}/api/v1/resources/{}?content=true".format(
floyd.floyd_host, instance_log_id)
floyd_logger.info(log_url)
return
if follow:
floyd_logger.info("Launching job ...")
follow_logs(instance_log_id, sleep_duration)
else:
log_file_contents = ResourceClient().get_content(instance_log_id)
if len(log_file_contents.strip()):
floyd_logger.info(log_file_contents.rstrip())
else:
floyd_logger.info("Launching job now. Try after a few seconds.") | python | def logs(id, url, follow, sleep_duration=1):
"""
View the logs of a job.
To follow along a job in real time, use the --follow flag
"""
instance_log_id = get_log_id(id)
if url:
log_url = "{}/api/v1/resources/{}?content=true".format(
floyd.floyd_host, instance_log_id)
floyd_logger.info(log_url)
return
if follow:
floyd_logger.info("Launching job ...")
follow_logs(instance_log_id, sleep_duration)
else:
log_file_contents = ResourceClient().get_content(instance_log_id)
if len(log_file_contents.strip()):
floyd_logger.info(log_file_contents.rstrip())
else:
floyd_logger.info("Launching job now. Try after a few seconds.") | [
"def",
"logs",
"(",
"id",
",",
"url",
",",
"follow",
",",
"sleep_duration",
"=",
"1",
")",
":",
"instance_log_id",
"=",
"get_log_id",
"(",
"id",
")",
"if",
"url",
":",
"log_url",
"=",
"\"{}/api/v1/resources/{}?content=true\"",
".",
"format",
"(",
"floyd",
... | View the logs of a job.
To follow along a job in real time, use the --follow flag | [
"View",
"the",
"logs",
"of",
"a",
"job",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L234-L256 | train | 23,184 |
floydhub/floyd-cli | floyd/cli/experiment.py | output | def output(id, url):
"""
View the files from a job.
"""
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
output_dir_url = "%s/%s/files" % (floyd.floyd_web_host, experiment.name)
if url:
floyd_logger.info(output_dir_url)
else:
floyd_logger.info("Opening output path in your browser ...")
webbrowser.open(output_dir_url) | python | def output(id, url):
"""
View the files from a job.
"""
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
output_dir_url = "%s/%s/files" % (floyd.floyd_web_host, experiment.name)
if url:
floyd_logger.info(output_dir_url)
else:
floyd_logger.info("Opening output path in your browser ...")
webbrowser.open(output_dir_url) | [
"def",
"output",
"(",
"id",
",",
"url",
")",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"id",
")",
")",
"except",
"FloydException",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
"... | View the files from a job. | [
"View",
"the",
"files",
"from",
"a",
"job",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L262-L276 | train | 23,185 |
floydhub/floyd-cli | floyd/cli/experiment.py | stop | def stop(id):
"""
Stop a running job.
"""
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
if experiment.state not in ["queued", "queue_scheduled", "running"]:
floyd_logger.info("Job in {} state cannot be stopped".format(experiment.state))
sys.exit(1)
if not ExperimentClient().stop(experiment.id):
floyd_logger.error("Failed to stop job")
sys.exit(1)
floyd_logger.info("Experiment shutdown request submitted. Check status to confirm shutdown") | python | def stop(id):
"""
Stop a running job.
"""
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
if experiment.state not in ["queued", "queue_scheduled", "running"]:
floyd_logger.info("Job in {} state cannot be stopped".format(experiment.state))
sys.exit(1)
if not ExperimentClient().stop(experiment.id):
floyd_logger.error("Failed to stop job")
sys.exit(1)
floyd_logger.info("Experiment shutdown request submitted. Check status to confirm shutdown") | [
"def",
"stop",
"(",
"id",
")",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"id",
")",
")",
"except",
"FloydException",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"("... | Stop a running job. | [
"Stop",
"a",
"running",
"job",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L281-L298 | train | 23,186 |
floydhub/floyd-cli | floyd/cli/experiment.py | delete | def delete(names, yes):
"""
Delete a training job.
"""
failures = False
for name in names:
try:
experiment = ExperimentClient().get(normalize_job_name(name))
except FloydException:
experiment = ExperimentClient().get(name)
if not experiment:
failures = True
continue
if not yes and not click.confirm("Delete Job: {}?".format(experiment.name),
abort=False,
default=False):
floyd_logger.info("Job {}: Skipped.".format(experiment.name))
continue
if not ExperimentClient().delete(experiment.id):
failures = True
else:
floyd_logger.info("Job %s Deleted", experiment.name)
if failures:
sys.exit(1) | python | def delete(names, yes):
"""
Delete a training job.
"""
failures = False
for name in names:
try:
experiment = ExperimentClient().get(normalize_job_name(name))
except FloydException:
experiment = ExperimentClient().get(name)
if not experiment:
failures = True
continue
if not yes and not click.confirm("Delete Job: {}?".format(experiment.name),
abort=False,
default=False):
floyd_logger.info("Job {}: Skipped.".format(experiment.name))
continue
if not ExperimentClient().delete(experiment.id):
failures = True
else:
floyd_logger.info("Job %s Deleted", experiment.name)
if failures:
sys.exit(1) | [
"def",
"delete",
"(",
"names",
",",
"yes",
")",
":",
"failures",
"=",
"False",
"for",
"name",
"in",
"names",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"name",
")",
")",
"except",
"Floy... | Delete a training job. | [
"Delete",
"a",
"training",
"job",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L304-L331 | train | 23,187 |
floydhub/floyd-cli | floyd/cli/version.py | version | def version():
"""
View the current version of the CLI.
"""
import pkg_resources
version = pkg_resources.require(PROJECT_NAME)[0].version
floyd_logger.info(version) | python | def version():
"""
View the current version of the CLI.
"""
import pkg_resources
version = pkg_resources.require(PROJECT_NAME)[0].version
floyd_logger.info(version) | [
"def",
"version",
"(",
")",
":",
"import",
"pkg_resources",
"version",
"=",
"pkg_resources",
".",
"require",
"(",
"PROJECT_NAME",
")",
"[",
"0",
"]",
".",
"version",
"floyd_logger",
".",
"info",
"(",
"version",
")"
] | View the current version of the CLI. | [
"View",
"the",
"current",
"version",
"of",
"the",
"CLI",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/version.py#L21-L27 | train | 23,188 |
floydhub/floyd-cli | floyd/cli/data.py | init | def init(dataset_name):
"""
Initialize a new dataset at the current dir.
Then run the upload command to copy all the files in this
directory to FloydHub.
floyd data upload
"""
dataset_obj = DatasetClient().get_by_name(dataset_name)
if not dataset_obj:
namespace, name = get_namespace_from_name(dataset_name)
create_dataset_base_url = "{}/datasets/create".format(floyd.floyd_web_host)
create_dataset_url = "{}?name={}&namespace={}".format(create_dataset_base_url, name, namespace)
floyd_logger.info(("Dataset name does not match your list of datasets. "
"Create your new dataset in the web dashboard:\n\t%s"),
create_dataset_base_url)
webbrowser.open(create_dataset_url)
name = click.prompt('Press ENTER to use dataset name "%s" or enter a different name' % dataset_name, default=dataset_name, show_default=False)
dataset_name = name.strip() or dataset_name
dataset_obj = DatasetClient().get_by_name(dataset_name)
if not dataset_obj:
raise FloydException('Dataset "%s" does not exist on floydhub.com. Ensure it exists before continuing.' % dataset_name)
namespace, name = get_namespace_from_name(dataset_name)
data_config = DataConfig(name=name,
namespace=namespace,
family_id=dataset_obj.id)
DataConfigManager.set_config(data_config)
floyd_logger.info("Data source \"{}\" initialized in current directory".format(dataset_name))
floyd_logger.info("""
You can now upload your data to Floyd by:
floyd data upload
""") | python | def init(dataset_name):
"""
Initialize a new dataset at the current dir.
Then run the upload command to copy all the files in this
directory to FloydHub.
floyd data upload
"""
dataset_obj = DatasetClient().get_by_name(dataset_name)
if not dataset_obj:
namespace, name = get_namespace_from_name(dataset_name)
create_dataset_base_url = "{}/datasets/create".format(floyd.floyd_web_host)
create_dataset_url = "{}?name={}&namespace={}".format(create_dataset_base_url, name, namespace)
floyd_logger.info(("Dataset name does not match your list of datasets. "
"Create your new dataset in the web dashboard:\n\t%s"),
create_dataset_base_url)
webbrowser.open(create_dataset_url)
name = click.prompt('Press ENTER to use dataset name "%s" or enter a different name' % dataset_name, default=dataset_name, show_default=False)
dataset_name = name.strip() or dataset_name
dataset_obj = DatasetClient().get_by_name(dataset_name)
if not dataset_obj:
raise FloydException('Dataset "%s" does not exist on floydhub.com. Ensure it exists before continuing.' % dataset_name)
namespace, name = get_namespace_from_name(dataset_name)
data_config = DataConfig(name=name,
namespace=namespace,
family_id=dataset_obj.id)
DataConfigManager.set_config(data_config)
floyd_logger.info("Data source \"{}\" initialized in current directory".format(dataset_name))
floyd_logger.info("""
You can now upload your data to Floyd by:
floyd data upload
""") | [
"def",
"init",
"(",
"dataset_name",
")",
":",
"dataset_obj",
"=",
"DatasetClient",
"(",
")",
".",
"get_by_name",
"(",
"dataset_name",
")",
"if",
"not",
"dataset_obj",
":",
"namespace",
",",
"name",
"=",
"get_namespace_from_name",
"(",
"dataset_name",
")",
"cre... | Initialize a new dataset at the current dir.
Then run the upload command to copy all the files in this
directory to FloydHub.
floyd data upload | [
"Initialize",
"a",
"new",
"dataset",
"at",
"the",
"current",
"dir",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L37-L74 | train | 23,189 |
floydhub/floyd-cli | floyd/cli/data.py | upload | def upload(resume, message):
"""
Upload files in the current dir to FloydHub.
"""
data_config = DataConfigManager.get_config()
if not upload_is_resumable(data_config) or not opt_to_resume(resume):
abort_previous_upload(data_config)
access_token = AuthConfigManager.get_access_token()
initialize_new_upload(data_config, access_token, message)
complete_upload(data_config) | python | def upload(resume, message):
"""
Upload files in the current dir to FloydHub.
"""
data_config = DataConfigManager.get_config()
if not upload_is_resumable(data_config) or not opt_to_resume(resume):
abort_previous_upload(data_config)
access_token = AuthConfigManager.get_access_token()
initialize_new_upload(data_config, access_token, message)
complete_upload(data_config) | [
"def",
"upload",
"(",
"resume",
",",
"message",
")",
":",
"data_config",
"=",
"DataConfigManager",
".",
"get_config",
"(",
")",
"if",
"not",
"upload_is_resumable",
"(",
"data_config",
")",
"or",
"not",
"opt_to_resume",
"(",
"resume",
")",
":",
"abort_previous_... | Upload files in the current dir to FloydHub. | [
"Upload",
"files",
"in",
"the",
"current",
"dir",
"to",
"FloydHub",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L82-L93 | train | 23,190 |
floydhub/floyd-cli | floyd/cli/data.py | status | def status(id):
"""
View status of all versions in a dataset.
The command also accepts a specific dataset version.
"""
if id:
data_source = get_data_object(id, use_data_config=False)
print_data([data_source] if data_source else [])
else:
data_sources = DataClient().get_all()
print_data(data_sources) | python | def status(id):
"""
View status of all versions in a dataset.
The command also accepts a specific dataset version.
"""
if id:
data_source = get_data_object(id, use_data_config=False)
print_data([data_source] if data_source else [])
else:
data_sources = DataClient().get_all()
print_data(data_sources) | [
"def",
"status",
"(",
"id",
")",
":",
"if",
"id",
":",
"data_source",
"=",
"get_data_object",
"(",
"id",
",",
"use_data_config",
"=",
"False",
")",
"print_data",
"(",
"[",
"data_source",
"]",
"if",
"data_source",
"else",
"[",
"]",
")",
"else",
":",
"da... | View status of all versions in a dataset.
The command also accepts a specific dataset version. | [
"View",
"status",
"of",
"all",
"versions",
"in",
"a",
"dataset",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L98-L109 | train | 23,191 |
floydhub/floyd-cli | floyd/cli/data.py | get_data_object | def get_data_object(data_id, use_data_config=True):
"""
Normalize the data_id and query the server.
If that is unavailable try the raw ID
"""
normalized_data_reference = normalize_data_name(data_id, use_data_config=use_data_config)
client = DataClient()
data_obj = client.get(normalized_data_reference)
# Try with the raw ID
if not data_obj and data_id != normalized_data_reference:
data_obj = client.get(data_id)
return data_obj | python | def get_data_object(data_id, use_data_config=True):
"""
Normalize the data_id and query the server.
If that is unavailable try the raw ID
"""
normalized_data_reference = normalize_data_name(data_id, use_data_config=use_data_config)
client = DataClient()
data_obj = client.get(normalized_data_reference)
# Try with the raw ID
if not data_obj and data_id != normalized_data_reference:
data_obj = client.get(data_id)
return data_obj | [
"def",
"get_data_object",
"(",
"data_id",
",",
"use_data_config",
"=",
"True",
")",
":",
"normalized_data_reference",
"=",
"normalize_data_name",
"(",
"data_id",
",",
"use_data_config",
"=",
"use_data_config",
")",
"client",
"=",
"DataClient",
"(",
")",
"data_obj",
... | Normalize the data_id and query the server.
If that is unavailable try the raw ID | [
"Normalize",
"the",
"data_id",
"and",
"query",
"the",
"server",
".",
"If",
"that",
"is",
"unavailable",
"try",
"the",
"raw",
"ID"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L112-L125 | train | 23,192 |
floydhub/floyd-cli | floyd/cli/data.py | print_data | def print_data(data_sources):
"""
Print dataset information in tabular form
"""
if not data_sources:
return
headers = ["DATA NAME", "CREATED", "STATUS", "DISK USAGE"]
data_list = []
for data_source in data_sources:
data_list.append([data_source.name,
data_source.created_pretty,
data_source.state, data_source.size])
floyd_logger.info(tabulate(data_list, headers=headers)) | python | def print_data(data_sources):
"""
Print dataset information in tabular form
"""
if not data_sources:
return
headers = ["DATA NAME", "CREATED", "STATUS", "DISK USAGE"]
data_list = []
for data_source in data_sources:
data_list.append([data_source.name,
data_source.created_pretty,
data_source.state, data_source.size])
floyd_logger.info(tabulate(data_list, headers=headers)) | [
"def",
"print_data",
"(",
"data_sources",
")",
":",
"if",
"not",
"data_sources",
":",
"return",
"headers",
"=",
"[",
"\"DATA NAME\"",
",",
"\"CREATED\"",
",",
"\"STATUS\"",
",",
"\"DISK USAGE\"",
"]",
"data_list",
"=",
"[",
"]",
"for",
"data_source",
"in",
"... | Print dataset information in tabular form | [
"Print",
"dataset",
"information",
"in",
"tabular",
"form"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L128-L141 | train | 23,193 |
floydhub/floyd-cli | floyd/cli/data.py | clone | def clone(id, path):
"""
- Download all files in a dataset or from a Job output
Eg: alice/projects/mnist/1/files, alice/projects/mnist/1/output or alice/dataset/mnist-data/1/
Using /output will download the files that are saved at the end of the job.
Note: This will download the files that are saved at
the end of the job.
- Download a directory from a dataset or from Job output
Specify the path to a directory and download all its files and subdirectories.
Eg: --path models/checkpoint1
"""
data_source = get_data_object(id, use_data_config=False)
if not data_source:
if 'output' in id:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
if path:
# Download a directory from Dataset or Files
# Get the type of data resource from the id (foo/projects/bar/ or foo/datasets/bar/)
if '/datasets/' in id:
resource_type = 'data'
resource_id = data_source.id
else:
resource_type = 'files'
try:
experiment = ExperimentClient().get(normalize_job_name(id, use_config=False))
except FloydException:
experiment = ExperimentClient().get(id)
resource_id = experiment.id
data_url = "{}/api/v1/download/artifacts/{}/{}?is_dir=true&path={}".format(floyd.floyd_host,
resource_type,
resource_id,
path)
else:
# Download the full Dataset
data_url = "{}/api/v1/resources/{}?content=true&download=true".format(floyd.floyd_host,
data_source.resource_id)
DataClient().download_tar(url=data_url,
untar=True,
delete_after_untar=True) | python | def clone(id, path):
"""
- Download all files in a dataset or from a Job output
Eg: alice/projects/mnist/1/files, alice/projects/mnist/1/output or alice/dataset/mnist-data/1/
Using /output will download the files that are saved at the end of the job.
Note: This will download the files that are saved at
the end of the job.
- Download a directory from a dataset or from Job output
Specify the path to a directory and download all its files and subdirectories.
Eg: --path models/checkpoint1
"""
data_source = get_data_object(id, use_data_config=False)
if not data_source:
if 'output' in id:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
if path:
# Download a directory from Dataset or Files
# Get the type of data resource from the id (foo/projects/bar/ or foo/datasets/bar/)
if '/datasets/' in id:
resource_type = 'data'
resource_id = data_source.id
else:
resource_type = 'files'
try:
experiment = ExperimentClient().get(normalize_job_name(id, use_config=False))
except FloydException:
experiment = ExperimentClient().get(id)
resource_id = experiment.id
data_url = "{}/api/v1/download/artifacts/{}/{}?is_dir=true&path={}".format(floyd.floyd_host,
resource_type,
resource_id,
path)
else:
# Download the full Dataset
data_url = "{}/api/v1/resources/{}?content=true&download=true".format(floyd.floyd_host,
data_source.resource_id)
DataClient().download_tar(url=data_url,
untar=True,
delete_after_untar=True) | [
"def",
"clone",
"(",
"id",
",",
"path",
")",
":",
"data_source",
"=",
"get_data_object",
"(",
"id",
",",
"use_data_config",
"=",
"False",
")",
"if",
"not",
"data_source",
":",
"if",
"'output'",
"in",
"id",
":",
"floyd_logger",
".",
"info",
"(",
"\"Note: ... | - Download all files in a dataset or from a Job output
Eg: alice/projects/mnist/1/files, alice/projects/mnist/1/output or alice/dataset/mnist-data/1/
Using /output will download the files that are saved at the end of the job.
Note: This will download the files that are saved at
the end of the job.
- Download a directory from a dataset or from Job output
Specify the path to a directory and download all its files and subdirectories.
Eg: --path models/checkpoint1 | [
"-",
"Download",
"all",
"files",
"in",
"a",
"dataset",
"or",
"from",
"a",
"Job",
"output"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L148-L196 | train | 23,194 |
floydhub/floyd-cli | floyd/cli/data.py | listfiles | def listfiles(data_name):
"""
List files in a dataset.
"""
data_source = get_data_object(data_name, use_data_config=False)
if not data_source:
if 'output' in data_name:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
# Depth-first search
dirs = ['']
paths = []
while dirs:
cur_dir = dirs.pop()
url = "/resources/{}/{}?content=true".format(data_source.resource_id, cur_dir)
response = DataClient().request("GET", url).json()
if response['skipped_files'] > 0:
floyd_logger.info("Warning: in directory '%s', %s/%s files skipped (too many files)", cur_dir, response['skipped_files'], response['total_files'])
files = response['files']
files.sort(key=lambda f: f['name'])
for f in files:
path = os.path.join(cur_dir, f['name'])
if f['type'] == 'directory':
path += os.sep
paths.append(path)
if f['type'] == 'directory':
dirs.append(os.path.join(cur_dir, f['name']))
for path in paths:
floyd_logger.info(path) | python | def listfiles(data_name):
"""
List files in a dataset.
"""
data_source = get_data_object(data_name, use_data_config=False)
if not data_source:
if 'output' in data_name:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
# Depth-first search
dirs = ['']
paths = []
while dirs:
cur_dir = dirs.pop()
url = "/resources/{}/{}?content=true".format(data_source.resource_id, cur_dir)
response = DataClient().request("GET", url).json()
if response['skipped_files'] > 0:
floyd_logger.info("Warning: in directory '%s', %s/%s files skipped (too many files)", cur_dir, response['skipped_files'], response['total_files'])
files = response['files']
files.sort(key=lambda f: f['name'])
for f in files:
path = os.path.join(cur_dir, f['name'])
if f['type'] == 'directory':
path += os.sep
paths.append(path)
if f['type'] == 'directory':
dirs.append(os.path.join(cur_dir, f['name']))
for path in paths:
floyd_logger.info(path) | [
"def",
"listfiles",
"(",
"data_name",
")",
":",
"data_source",
"=",
"get_data_object",
"(",
"data_name",
",",
"use_data_config",
"=",
"False",
")",
"if",
"not",
"data_source",
":",
"if",
"'output'",
"in",
"data_name",
":",
"floyd_logger",
".",
"info",
"(",
"... | List files in a dataset. | [
"List",
"files",
"in",
"a",
"dataset",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L201-L235 | train | 23,195 |
floydhub/floyd-cli | floyd/cli/data.py | getfile | def getfile(data_name, path):
"""
Download a specific file from a dataset.
"""
data_source = get_data_object(data_name, use_data_config=False)
if not data_source:
if 'output' in data_name:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
url = "{}/api/v1/resources/{}/{}?content=true".format(floyd.floyd_host, data_source.resource_id, path)
fname = os.path.basename(path)
DataClient().download(url, filename=fname)
floyd_logger.info("Download finished") | python | def getfile(data_name, path):
"""
Download a specific file from a dataset.
"""
data_source = get_data_object(data_name, use_data_config=False)
if not data_source:
if 'output' in data_name:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
url = "{}/api/v1/resources/{}/{}?content=true".format(floyd.floyd_host, data_source.resource_id, path)
fname = os.path.basename(path)
DataClient().download(url, filename=fname)
floyd_logger.info("Download finished") | [
"def",
"getfile",
"(",
"data_name",
",",
"path",
")",
":",
"data_source",
"=",
"get_data_object",
"(",
"data_name",
",",
"use_data_config",
"=",
"False",
")",
"if",
"not",
"data_source",
":",
"if",
"'output'",
"in",
"data_name",
":",
"floyd_logger",
".",
"in... | Download a specific file from a dataset. | [
"Download",
"a",
"specific",
"file",
"from",
"a",
"dataset",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L241-L256 | train | 23,196 |
floydhub/floyd-cli | floyd/cli/data.py | output | def output(id, url):
"""
View the files from a dataset.
"""
data_source = get_data_object(id, use_data_config=False)
if not data_source:
sys.exit()
data_url = "%s/%s" % (floyd.floyd_web_host, data_source.name)
if url:
floyd_logger.info(data_url)
else:
floyd_logger.info("Opening output directory in your browser ...")
webbrowser.open(data_url) | python | def output(id, url):
"""
View the files from a dataset.
"""
data_source = get_data_object(id, use_data_config=False)
if not data_source:
sys.exit()
data_url = "%s/%s" % (floyd.floyd_web_host, data_source.name)
if url:
floyd_logger.info(data_url)
else:
floyd_logger.info("Opening output directory in your browser ...")
webbrowser.open(data_url) | [
"def",
"output",
"(",
"id",
",",
"url",
")",
":",
"data_source",
"=",
"get_data_object",
"(",
"id",
",",
"use_data_config",
"=",
"False",
")",
"if",
"not",
"data_source",
":",
"sys",
".",
"exit",
"(",
")",
"data_url",
"=",
"\"%s/%s\"",
"%",
"(",
"floyd... | View the files from a dataset. | [
"View",
"the",
"files",
"from",
"a",
"dataset",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L263-L277 | train | 23,197 |
floydhub/floyd-cli | floyd/cli/data.py | delete | def delete(ids, yes):
"""
Delete datasets.
"""
failures = False
for id in ids:
data_source = get_data_object(id, use_data_config=True)
if not data_source:
failures = True
continue
data_name = normalize_data_name(data_source.name)
suffix = data_name.split('/')[-1]
if not suffix.isdigit():
failures = True
floyd_logger.error('%s is not a dataset, skipped.', id)
if suffix == 'output':
floyd_logger.error('To delete job output, please delete the job itself.')
continue
if not yes and not click.confirm("Delete Data: {}?".format(data_name),
abort=False,
default=False):
floyd_logger.info("Data %s: Skipped", data_name)
continue
if not DataClient().delete(data_source.id):
failures = True
else:
floyd_logger.info("Data %s: Deleted", data_name)
if failures:
sys.exit(1) | python | def delete(ids, yes):
"""
Delete datasets.
"""
failures = False
for id in ids:
data_source = get_data_object(id, use_data_config=True)
if not data_source:
failures = True
continue
data_name = normalize_data_name(data_source.name)
suffix = data_name.split('/')[-1]
if not suffix.isdigit():
failures = True
floyd_logger.error('%s is not a dataset, skipped.', id)
if suffix == 'output':
floyd_logger.error('To delete job output, please delete the job itself.')
continue
if not yes and not click.confirm("Delete Data: {}?".format(data_name),
abort=False,
default=False):
floyd_logger.info("Data %s: Skipped", data_name)
continue
if not DataClient().delete(data_source.id):
failures = True
else:
floyd_logger.info("Data %s: Deleted", data_name)
if failures:
sys.exit(1) | [
"def",
"delete",
"(",
"ids",
",",
"yes",
")",
":",
"failures",
"=",
"False",
"for",
"id",
"in",
"ids",
":",
"data_source",
"=",
"get_data_object",
"(",
"id",
",",
"use_data_config",
"=",
"True",
")",
"if",
"not",
"data_source",
":",
"failures",
"=",
"T... | Delete datasets. | [
"Delete",
"datasets",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L284-L318 | train | 23,198 |
floydhub/floyd-cli | floyd/cli/data.py | add | def add(source):
"""
Create a new dataset version from the contents of a job.
This will create a new dataset version with the job output.
Use the full job name: foo/projects/bar/1/code, foo/projects/bar/1/files or foo/projects/bar/1/output
"""
new_data = DatasetClient().add_data(source)
print_data([DataClient().get(new_data['data_id'])]) | python | def add(source):
"""
Create a new dataset version from the contents of a job.
This will create a new dataset version with the job output.
Use the full job name: foo/projects/bar/1/code, foo/projects/bar/1/files or foo/projects/bar/1/output
"""
new_data = DatasetClient().add_data(source)
print_data([DataClient().get(new_data['data_id'])]) | [
"def",
"add",
"(",
"source",
")",
":",
"new_data",
"=",
"DatasetClient",
"(",
")",
".",
"add_data",
"(",
"source",
")",
"print_data",
"(",
"[",
"DataClient",
"(",
")",
".",
"get",
"(",
"new_data",
"[",
"'data_id'",
"]",
")",
"]",
")"
] | Create a new dataset version from the contents of a job.
This will create a new dataset version with the job output.
Use the full job name: foo/projects/bar/1/code, foo/projects/bar/1/files or foo/projects/bar/1/output | [
"Create",
"a",
"new",
"dataset",
"version",
"from",
"the",
"contents",
"of",
"a",
"job",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L323-L331 | train | 23,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.