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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
niklasf/python-chess | chess/pgn.py | GameNode.end | def end(self) -> "GameNode":
"""Follows the main variation to the end and returns the last node."""
node = self
while node.variations:
node = node.variations[0]
return node | python | def end(self) -> "GameNode":
"""Follows the main variation to the end and returns the last node."""
node = self
while node.variations:
node = node.variations[0]
return node | [
"def",
"end",
"(",
"self",
")",
"->",
"\"GameNode\"",
":",
"node",
"=",
"self",
"while",
"node",
".",
"variations",
":",
"node",
"=",
"node",
".",
"variations",
"[",
"0",
"]",
"return",
"node"
] | Follows the main variation to the end and returns the last node. | [
"Follows",
"the",
"main",
"variation",
"to",
"the",
"end",
"and",
"returns",
"the",
"last",
"node",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L186-L193 | train | 219,700 |
niklasf/python-chess | chess/pgn.py | GameNode.is_mainline | def is_mainline(self) -> bool:
"""Checks if the node is in the mainline of the game."""
node = self
while node.parent:
parent = node.parent
if not parent.variations or parent.variations[0] != node:
return False
node = parent
return True | python | def is_mainline(self) -> bool:
"""Checks if the node is in the mainline of the game."""
node = self
while node.parent:
parent = node.parent
if not parent.variations or parent.variations[0] != node:
return False
node = parent
return True | [
"def",
"is_mainline",
"(",
"self",
")",
"->",
"bool",
":",
"node",
"=",
"self",
"while",
"node",
".",
"parent",
":",
"parent",
"=",
"node",
".",
"parent",
"if",
"not",
"parent",
".",
"variations",
"or",
"parent",
".",
"variations",
"[",
"0",
"]",
"!=... | Checks if the node is in the mainline of the game. | [
"Checks",
"if",
"the",
"node",
"is",
"in",
"the",
"mainline",
"of",
"the",
"game",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L213-L225 | train | 219,701 |
niklasf/python-chess | chess/pgn.py | GameNode.is_main_variation | def is_main_variation(self) -> bool:
"""
Checks if this node is the first variation from the point of view of its
parent. The root node is also in the main variation.
"""
if not self.parent:
return True
return not self.parent.variations or self.parent.variations[0] == self | python | def is_main_variation(self) -> bool:
"""
Checks if this node is the first variation from the point of view of its
parent. The root node is also in the main variation.
"""
if not self.parent:
return True
return not self.parent.variations or self.parent.variations[0] == self | [
"def",
"is_main_variation",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"True",
"return",
"not",
"self",
".",
"parent",
".",
"variations",
"or",
"self",
".",
"parent",
".",
"variations",
"[",
"0",
"]",
"==",
... | Checks if this node is the first variation from the point of view of its
parent. The root node is also in the main variation. | [
"Checks",
"if",
"this",
"node",
"is",
"the",
"first",
"variation",
"from",
"the",
"point",
"of",
"view",
"of",
"its",
"parent",
".",
"The",
"root",
"node",
"is",
"also",
"in",
"the",
"main",
"variation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L227-L235 | train | 219,702 |
niklasf/python-chess | chess/pgn.py | GameNode.promote | def promote(self, move: chess.Move) -> None:
"""Moves a variation one up in the list of variations."""
variation = self[move]
i = self.variations.index(variation)
if i > 0:
self.variations[i - 1], self.variations[i] = self.variations[i], self.variations[i - 1] | python | def promote(self, move: chess.Move) -> None:
"""Moves a variation one up in the list of variations."""
variation = self[move]
i = self.variations.index(variation)
if i > 0:
self.variations[i - 1], self.variations[i] = self.variations[i], self.variations[i - 1] | [
"def",
"promote",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
")",
"->",
"None",
":",
"variation",
"=",
"self",
"[",
"move",
"]",
"i",
"=",
"self",
".",
"variations",
".",
"index",
"(",
"variation",
")",
"if",
"i",
">",
"0",
":",
"self",... | Moves a variation one up in the list of variations. | [
"Moves",
"a",
"variation",
"one",
"up",
"in",
"the",
"list",
"of",
"variations",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L263-L268 | train | 219,703 |
niklasf/python-chess | chess/pgn.py | GameNode.demote | def demote(self, move: chess.Move) -> None:
"""Moves a variation one down in the list of variations."""
variation = self[move]
i = self.variations.index(variation)
if i < len(self.variations) - 1:
self.variations[i + 1], self.variations[i] = self.variations[i], self.variations[i + 1] | python | def demote(self, move: chess.Move) -> None:
"""Moves a variation one down in the list of variations."""
variation = self[move]
i = self.variations.index(variation)
if i < len(self.variations) - 1:
self.variations[i + 1], self.variations[i] = self.variations[i], self.variations[i + 1] | [
"def",
"demote",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
")",
"->",
"None",
":",
"variation",
"=",
"self",
"[",
"move",
"]",
"i",
"=",
"self",
".",
"variations",
".",
"index",
"(",
"variation",
")",
"if",
"i",
"<",
"len",
"(",
"self"... | Moves a variation one down in the list of variations. | [
"Moves",
"a",
"variation",
"one",
"down",
"in",
"the",
"list",
"of",
"variations",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L270-L275 | train | 219,704 |
niklasf/python-chess | chess/pgn.py | GameNode.remove_variation | def remove_variation(self, move: chess.Move) -> None:
"""Removes a variation."""
self.variations.remove(self.variation(move)) | python | def remove_variation(self, move: chess.Move) -> None:
"""Removes a variation."""
self.variations.remove(self.variation(move)) | [
"def",
"remove_variation",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
")",
"->",
"None",
":",
"self",
".",
"variations",
".",
"remove",
"(",
"self",
".",
"variation",
"(",
"move",
")",
")"
] | Removes a variation. | [
"Removes",
"a",
"variation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L277-L279 | train | 219,705 |
niklasf/python-chess | chess/pgn.py | GameNode.add_variation | def add_variation(self, move: chess.Move, *, comment: str = "", starting_comment: str = "", nags: Iterable[int] = ()) -> "GameNode":
"""Creates a child node with the given attributes."""
node = type(self).dangling_node()
node.move = move
node.nags = set(nags)
node.comment = comment
node.starting_comment = starting_comment
node.parent = self
self.variations.append(node)
return node | python | def add_variation(self, move: chess.Move, *, comment: str = "", starting_comment: str = "", nags: Iterable[int] = ()) -> "GameNode":
"""Creates a child node with the given attributes."""
node = type(self).dangling_node()
node.move = move
node.nags = set(nags)
node.comment = comment
node.starting_comment = starting_comment
node.parent = self
self.variations.append(node)
return node | [
"def",
"add_variation",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
",",
"*",
",",
"comment",
":",
"str",
"=",
"\"\"",
",",
"starting_comment",
":",
"str",
"=",
"\"\"",
",",
"nags",
":",
"Iterable",
"[",
"int",
"]",
"=",
"(",
")",
")",
"... | Creates a child node with the given attributes. | [
"Creates",
"a",
"child",
"node",
"with",
"the",
"given",
"attributes",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L281-L291 | train | 219,706 |
niklasf/python-chess | chess/pgn.py | GameNode.add_main_variation | def add_main_variation(self, move: chess.Move, *, comment: str = "") -> "GameNode":
"""
Creates a child node with the given attributes and promotes it to the
main variation.
"""
node = self.add_variation(move, comment=comment)
self.variations.remove(node)
self.variations.insert(0, node)
return node | python | def add_main_variation(self, move: chess.Move, *, comment: str = "") -> "GameNode":
"""
Creates a child node with the given attributes and promotes it to the
main variation.
"""
node = self.add_variation(move, comment=comment)
self.variations.remove(node)
self.variations.insert(0, node)
return node | [
"def",
"add_main_variation",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
",",
"*",
",",
"comment",
":",
"str",
"=",
"\"\"",
")",
"->",
"\"GameNode\"",
":",
"node",
"=",
"self",
".",
"add_variation",
"(",
"move",
",",
"comment",
"=",
"comment",... | Creates a child node with the given attributes and promotes it to the
main variation. | [
"Creates",
"a",
"child",
"node",
"with",
"the",
"given",
"attributes",
"and",
"promotes",
"it",
"to",
"the",
"main",
"variation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L293-L301 | train | 219,707 |
niklasf/python-chess | chess/pgn.py | Game.board | def board(self, *, _cache: bool = False) -> chess.Board:
"""
Gets the starting position of the game.
Unless the ``FEN`` header tag is set, this is the default starting
position (for the ``Variant``).
"""
return self.headers.board() | python | def board(self, *, _cache: bool = False) -> chess.Board:
"""
Gets the starting position of the game.
Unless the ``FEN`` header tag is set, this is the default starting
position (for the ``Variant``).
"""
return self.headers.board() | [
"def",
"board",
"(",
"self",
",",
"*",
",",
"_cache",
":",
"bool",
"=",
"False",
")",
"->",
"chess",
".",
"Board",
":",
"return",
"self",
".",
"headers",
".",
"board",
"(",
")"
] | Gets the starting position of the game.
Unless the ``FEN`` header tag is set, this is the default starting
position (for the ``Variant``). | [
"Gets",
"the",
"starting",
"position",
"of",
"the",
"game",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L432-L439 | train | 219,708 |
niklasf/python-chess | chess/pgn.py | BaseVisitor.parse_san | def parse_san(self, board: chess.Board, san: str) -> chess.Move:
"""
When the visitor is used by a parser, this is called to parse a move
in standard algebraic notation.
You can override the default implementation to work around specific
quirks of your input format.
"""
# Replace zeros with correct castling notation.
if san == "0-0":
san = "O-O"
elif san == "0-0-0":
san = "O-O-O"
return board.parse_san(san) | python | def parse_san(self, board: chess.Board, san: str) -> chess.Move:
"""
When the visitor is used by a parser, this is called to parse a move
in standard algebraic notation.
You can override the default implementation to work around specific
quirks of your input format.
"""
# Replace zeros with correct castling notation.
if san == "0-0":
san = "O-O"
elif san == "0-0-0":
san = "O-O-O"
return board.parse_san(san) | [
"def",
"parse_san",
"(",
"self",
",",
"board",
":",
"chess",
".",
"Board",
",",
"san",
":",
"str",
")",
"->",
"chess",
".",
"Move",
":",
"# Replace zeros with correct castling notation.",
"if",
"san",
"==",
"\"0-0\"",
":",
"san",
"=",
"\"O-O\"",
"elif",
"s... | When the visitor is used by a parser, this is called to parse a move
in standard algebraic notation.
You can override the default implementation to work around specific
quirks of your input format. | [
"When",
"the",
"visitor",
"is",
"used",
"by",
"a",
"parser",
"this",
"is",
"called",
"to",
"parse",
"a",
"move",
"in",
"standard",
"algebraic",
"notation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L710-L724 | train | 219,709 |
niklasf/python-chess | setup.py | read_description | def read_description():
"""
Reads the description from README.rst and substitutes mentions of the
latest version with a concrete version number.
"""
with open(os.path.join(os.path.dirname(__file__), "README.rst"), encoding="utf-8") as f:
description = f.read()
# Link to the documentation of the specific version.
description = description.replace(
"//python-chess.readthedocs.io/en/latest/",
"//python-chess.readthedocs.io/en/v{}/".format(chess.__version__))
# Use documentation badge for the specific version.
description = description.replace(
"//readthedocs.org/projects/python-chess/badge/?version=latest",
"//readthedocs.org/projects/python-chess/badge/?version=v{}".format(chess.__version__))
# Show Travis CI build status of the concrete version.
description = description.replace(
"//travis-ci.org/niklasf/python-chess.svg?branch=master",
"//travis-ci.org/niklasf/python-chess.svg?branch=v{}".format(chess.__version__))
# Show Appveyor build status of the concrete version.
description = description.replace(
"/y9k3hdbm0f0nbum9/branch/master",
"/y9k3hdbm0f0nbum9/branch/v{}".format(chess.__version__))
# Remove doctest comments.
description = re.sub(r"\s*# doctest:.*", "", description)
return description | python | def read_description():
"""
Reads the description from README.rst and substitutes mentions of the
latest version with a concrete version number.
"""
with open(os.path.join(os.path.dirname(__file__), "README.rst"), encoding="utf-8") as f:
description = f.read()
# Link to the documentation of the specific version.
description = description.replace(
"//python-chess.readthedocs.io/en/latest/",
"//python-chess.readthedocs.io/en/v{}/".format(chess.__version__))
# Use documentation badge for the specific version.
description = description.replace(
"//readthedocs.org/projects/python-chess/badge/?version=latest",
"//readthedocs.org/projects/python-chess/badge/?version=v{}".format(chess.__version__))
# Show Travis CI build status of the concrete version.
description = description.replace(
"//travis-ci.org/niklasf/python-chess.svg?branch=master",
"//travis-ci.org/niklasf/python-chess.svg?branch=v{}".format(chess.__version__))
# Show Appveyor build status of the concrete version.
description = description.replace(
"/y9k3hdbm0f0nbum9/branch/master",
"/y9k3hdbm0f0nbum9/branch/v{}".format(chess.__version__))
# Remove doctest comments.
description = re.sub(r"\s*# doctest:.*", "", description)
return description | [
"def",
"read_description",
"(",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"README.rst\"",
")",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"f",
":",
"descript... | Reads the description from README.rst and substitutes mentions of the
latest version with a concrete version number. | [
"Reads",
"the",
"description",
"from",
"README",
".",
"rst",
"and",
"substitutes",
"mentions",
"of",
"the",
"latest",
"version",
"with",
"a",
"concrete",
"version",
"number",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/setup.py#L40-L71 | train | 219,710 |
niklasf/python-chess | chess/engine.py | popen_uci | async def popen_uci(command: Union[str, List[str]], *, setpgrp: bool = False, loop=None, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, UciProtocol]:
"""
Spawns and initializes an UCI engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair.
"""
transport, protocol = await UciProtocol.popen(command, setpgrp=setpgrp, loop=loop, **popen_args)
try:
await protocol.initialize()
except:
transport.close()
raise
return transport, protocol | python | async def popen_uci(command: Union[str, List[str]], *, setpgrp: bool = False, loop=None, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, UciProtocol]:
"""
Spawns and initializes an UCI engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair.
"""
transport, protocol = await UciProtocol.popen(command, setpgrp=setpgrp, loop=loop, **popen_args)
try:
await protocol.initialize()
except:
transport.close()
raise
return transport, protocol | [
"async",
"def",
"popen_uci",
"(",
"command",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
",",
"*",
",",
"setpgrp",
":",
"bool",
"=",
"False",
",",
"loop",
"=",
"None",
",",
"*",
"*",
"popen_args",
":",
"Any",
")",
"->",
"Tuple",
... | Spawns and initializes an UCI engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair. | [
"Spawns",
"and",
"initializes",
"an",
"UCI",
"engine",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2158-L2180 | train | 219,711 |
niklasf/python-chess | chess/engine.py | popen_xboard | async def popen_xboard(command: Union[str, List[str]], *, setpgrp: bool = False, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, XBoardProtocol]:
"""
Spawns and initializes an XBoard engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair.
"""
transport, protocol = await XBoardProtocol.popen(command, setpgrp=setpgrp, **popen_args)
try:
await protocol.initialize()
except:
transport.close()
raise
return transport, protocol | python | async def popen_xboard(command: Union[str, List[str]], *, setpgrp: bool = False, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, XBoardProtocol]:
"""
Spawns and initializes an XBoard engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair.
"""
transport, protocol = await XBoardProtocol.popen(command, setpgrp=setpgrp, **popen_args)
try:
await protocol.initialize()
except:
transport.close()
raise
return transport, protocol | [
"async",
"def",
"popen_xboard",
"(",
"command",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
",",
"*",
",",
"setpgrp",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"popen_args",
":",
"Any",
")",
"->",
"Tuple",
"[",
"asyncio",
".",
"S... | Spawns and initializes an XBoard engine.
:param command: Path of the engine executable, or a list including the
path and arguments.
:param setpgrp: Open the engine process in a new process group. This will
stop signals (such as keyboard interrupts) from propagating from the
parent process. Defaults to ``False``.
:param popen_args: Additional arguments for
`popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_.
Do not set ``stdin``, ``stdout``, ``bufsize`` or
``universal_newlines``.
Returns a subprocess transport and engine protocol pair. | [
"Spawns",
"and",
"initializes",
"an",
"XBoard",
"engine",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2183-L2205 | train | 219,712 |
niklasf/python-chess | chess/engine.py | UciProtocol.debug | def debug(self, on: bool = True) -> None:
"""
Switches debug mode of the engine on or off. This does not interrupt
other ongoing operations.
"""
if on:
self.send_line("debug on")
else:
self.send_line("debug off") | python | def debug(self, on: bool = True) -> None:
"""
Switches debug mode of the engine on or off. This does not interrupt
other ongoing operations.
"""
if on:
self.send_line("debug on")
else:
self.send_line("debug off") | [
"def",
"debug",
"(",
"self",
",",
"on",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"on",
":",
"self",
".",
"send_line",
"(",
"\"debug on\"",
")",
"else",
":",
"self",
".",
"send_line",
"(",
"\"debug off\"",
")"
] | Switches debug mode of the engine on or off. This does not interrupt
other ongoing operations. | [
"Switches",
"debug",
"mode",
"of",
"the",
"engine",
"on",
"or",
"off",
".",
"This",
"does",
"not",
"interrupt",
"other",
"ongoing",
"operations",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L1024-L1032 | train | 219,713 |
niklasf/python-chess | chess/engine.py | AnalysisResult.stop | def stop(self) -> None:
"""Stops the analysis as soon as possible."""
if self._stop and not self._posted_kork:
self._stop()
self._stop = None | python | def stop(self) -> None:
"""Stops the analysis as soon as possible."""
if self._stop and not self._posted_kork:
self._stop()
self._stop = None | [
"def",
"stop",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_stop",
"and",
"not",
"self",
".",
"_posted_kork",
":",
"self",
".",
"_stop",
"(",
")",
"self",
".",
"_stop",
"=",
"None"
] | Stops the analysis as soon as possible. | [
"Stops",
"the",
"analysis",
"as",
"soon",
"as",
"possible",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2090-L2094 | train | 219,714 |
niklasf/python-chess | chess/engine.py | AnalysisResult.get | async def get(self) -> InfoDict:
"""
Waits for the next dictionary of information from the engine and
returns it.
It might be more convenient to use ``async for info in analysis: ...``.
:raises: :exc:`chess.engine.AnalysisComplete` if the analysis is
complete (or has been stopped) and all information has been
consumed. Use :func:`~chess.engine.AnalysisResult.next()` if you
prefer to get ``None`` instead of an exception.
"""
if self._seen_kork:
raise AnalysisComplete()
info = await self._queue.get()
if not info:
# Empty dictionary marks end.
self._seen_kork = True
await self._finished
raise AnalysisComplete()
return info | python | async def get(self) -> InfoDict:
"""
Waits for the next dictionary of information from the engine and
returns it.
It might be more convenient to use ``async for info in analysis: ...``.
:raises: :exc:`chess.engine.AnalysisComplete` if the analysis is
complete (or has been stopped) and all information has been
consumed. Use :func:`~chess.engine.AnalysisResult.next()` if you
prefer to get ``None`` instead of an exception.
"""
if self._seen_kork:
raise AnalysisComplete()
info = await self._queue.get()
if not info:
# Empty dictionary marks end.
self._seen_kork = True
await self._finished
raise AnalysisComplete()
return info | [
"async",
"def",
"get",
"(",
"self",
")",
"->",
"InfoDict",
":",
"if",
"self",
".",
"_seen_kork",
":",
"raise",
"AnalysisComplete",
"(",
")",
"info",
"=",
"await",
"self",
".",
"_queue",
".",
"get",
"(",
")",
"if",
"not",
"info",
":",
"# Empty dictionar... | Waits for the next dictionary of information from the engine and
returns it.
It might be more convenient to use ``async for info in analysis: ...``.
:raises: :exc:`chess.engine.AnalysisComplete` if the analysis is
complete (or has been stopped) and all information has been
consumed. Use :func:`~chess.engine.AnalysisResult.next()` if you
prefer to get ``None`` instead of an exception. | [
"Waits",
"for",
"the",
"next",
"dictionary",
"of",
"information",
"from",
"the",
"engine",
"and",
"returns",
"it",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2100-L2122 | train | 219,715 |
niklasf/python-chess | chess/engine.py | AnalysisResult.empty | def empty(self) -> bool:
"""
Checks if all information has been consumed.
If the queue is empty, but the analysis is still ongoing, then further
information can become available in the future.
If the queue is not empty, then the next call to
:func:`~chess.engine.AnalysisResult.get()` will return instantly.
"""
return self._seen_kork or self._queue.qsize() <= self._posted_kork | python | def empty(self) -> bool:
"""
Checks if all information has been consumed.
If the queue is empty, but the analysis is still ongoing, then further
information can become available in the future.
If the queue is not empty, then the next call to
:func:`~chess.engine.AnalysisResult.get()` will return instantly.
"""
return self._seen_kork or self._queue.qsize() <= self._posted_kork | [
"def",
"empty",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_seen_kork",
"or",
"self",
".",
"_queue",
".",
"qsize",
"(",
")",
"<=",
"self",
".",
"_posted_kork"
] | Checks if all information has been consumed.
If the queue is empty, but the analysis is still ongoing, then further
information can become available in the future.
If the queue is not empty, then the next call to
:func:`~chess.engine.AnalysisResult.get()` will return instantly. | [
"Checks",
"if",
"all",
"information",
"has",
"been",
"consumed",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2124-L2134 | train | 219,716 |
niklasf/python-chess | chess/engine.py | SimpleEngine.close | def close(self) -> None:
"""
Closes the transport and the background event loop as soon as possible.
"""
def _shutdown() -> None:
self.transport.close()
self.shutdown_event.set()
with self._shutdown_lock:
if not self._shutdown:
self._shutdown = True
self.protocol.loop.call_soon_threadsafe(_shutdown) | python | def close(self) -> None:
"""
Closes the transport and the background event loop as soon as possible.
"""
def _shutdown() -> None:
self.transport.close()
self.shutdown_event.set()
with self._shutdown_lock:
if not self._shutdown:
self._shutdown = True
self.protocol.loop.call_soon_threadsafe(_shutdown) | [
"def",
"close",
"(",
"self",
")",
"->",
"None",
":",
"def",
"_shutdown",
"(",
")",
"->",
"None",
":",
"self",
".",
"transport",
".",
"close",
"(",
")",
"self",
".",
"shutdown_event",
".",
"set",
"(",
")",
"with",
"self",
".",
"_shutdown_lock",
":",
... | Closes the transport and the background event loop as soon as possible. | [
"Closes",
"the",
"transport",
"and",
"the",
"background",
"event",
"loop",
"as",
"soon",
"as",
"possible",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2314-L2325 | train | 219,717 |
niklasf/python-chess | chess/gaviota.py | open_tablebase_native | def open_tablebase_native(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> NativeTablebase:
"""
Opens a collection of tables for probing using libgtb.
In most cases :func:`~chess.gaviota.open_tablebase()` should be used.
Use this function only if you do not want to downgrade to pure Python
tablebase probing.
:raises: :exc:`RuntimeError` or :exc:`OSError` when libgtb can not be used.
"""
libgtb = libgtb or ctypes.util.find_library("gtb") or "libgtb.so.1.0.1"
tables = NativeTablebase(LibraryLoader.LoadLibrary(libgtb))
tables.add_directory(directory)
return tables | python | def open_tablebase_native(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> NativeTablebase:
"""
Opens a collection of tables for probing using libgtb.
In most cases :func:`~chess.gaviota.open_tablebase()` should be used.
Use this function only if you do not want to downgrade to pure Python
tablebase probing.
:raises: :exc:`RuntimeError` or :exc:`OSError` when libgtb can not be used.
"""
libgtb = libgtb or ctypes.util.find_library("gtb") or "libgtb.so.1.0.1"
tables = NativeTablebase(LibraryLoader.LoadLibrary(libgtb))
tables.add_directory(directory)
return tables | [
"def",
"open_tablebase_native",
"(",
"directory",
":",
"PathLike",
",",
"*",
",",
"libgtb",
":",
"Any",
"=",
"None",
",",
"LibraryLoader",
":",
"Any",
"=",
"ctypes",
".",
"cdll",
")",
"->",
"NativeTablebase",
":",
"libgtb",
"=",
"libgtb",
"or",
"ctypes",
... | Opens a collection of tables for probing using libgtb.
In most cases :func:`~chess.gaviota.open_tablebase()` should be used.
Use this function only if you do not want to downgrade to pure Python
tablebase probing.
:raises: :exc:`RuntimeError` or :exc:`OSError` when libgtb can not be used. | [
"Opens",
"a",
"collection",
"of",
"tables",
"for",
"probing",
"using",
"libgtb",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/gaviota.py#L2083-L2096 | train | 219,718 |
niklasf/python-chess | chess/gaviota.py | open_tablebase | def open_tablebase(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> Union[NativeTablebase, PythonTablebase]:
"""
Opens a collection of tables for probing.
First native access via the shared library libgtb is tried. You can
optionally provide a specific library name or a library loader.
The shared library has global state and caches, so only one instance can
be open at a time.
Second, pure Python probing code is tried.
"""
try:
if LibraryLoader:
return open_tablebase_native(directory, libgtb=libgtb, LibraryLoader=LibraryLoader)
except (OSError, RuntimeError) as err:
LOGGER.info("Falling back to pure Python tablebase: %r", err)
tables = PythonTablebase()
tables.add_directory(directory)
return tables | python | def open_tablebase(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> Union[NativeTablebase, PythonTablebase]:
"""
Opens a collection of tables for probing.
First native access via the shared library libgtb is tried. You can
optionally provide a specific library name or a library loader.
The shared library has global state and caches, so only one instance can
be open at a time.
Second, pure Python probing code is tried.
"""
try:
if LibraryLoader:
return open_tablebase_native(directory, libgtb=libgtb, LibraryLoader=LibraryLoader)
except (OSError, RuntimeError) as err:
LOGGER.info("Falling back to pure Python tablebase: %r", err)
tables = PythonTablebase()
tables.add_directory(directory)
return tables | [
"def",
"open_tablebase",
"(",
"directory",
":",
"PathLike",
",",
"*",
",",
"libgtb",
":",
"Any",
"=",
"None",
",",
"LibraryLoader",
":",
"Any",
"=",
"ctypes",
".",
"cdll",
")",
"->",
"Union",
"[",
"NativeTablebase",
",",
"PythonTablebase",
"]",
":",
"try... | Opens a collection of tables for probing.
First native access via the shared library libgtb is tried. You can
optionally provide a specific library name or a library loader.
The shared library has global state and caches, so only one instance can
be open at a time.
Second, pure Python probing code is tried. | [
"Opens",
"a",
"collection",
"of",
"tables",
"for",
"probing",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/gaviota.py#L2099-L2118 | train | 219,719 |
niklasf/python-chess | chess/gaviota.py | PythonTablebase.probe_dtm | def probe_dtm(self, board: chess.Board) -> int:
"""
Probes for depth to mate information.
The absolute value is the number of half-moves until forced mate
(or ``0`` in drawn positions). The value is positive if the
side to move is winning, otherwise it is negative.
In the example position white to move will get mated in 10 half-moves:
>>> import chess
>>> import chess.gaviota
>>>
>>> with chess.gaviota.open_tablebase("data/gaviota") as tablebase:
... board = chess.Board("8/8/8/8/8/8/8/K2kr3 w - - 0 1")
... print(tablebase.probe_dtm(board))
...
-10
:raises: :exc:`KeyError` (or specifically
:exc:`chess.gaviota.MissingTableError`) if the probe fails. Use
:func:`~chess.gaviota.PythonTablebase.get_dtm()` if you prefer
to get ``None`` instead of an exception.
Note that probing a corrupted table file is undefined behavior.
"""
# Can not probe positions with castling rights.
if board.castling_rights:
raise KeyError("gaviota tables do not contain positions with castling rights: {}".format(board.fen()))
# Supports only up to 5 pieces.
if chess.popcount(board.occupied) > 5:
raise KeyError("gaviota tables support up to 5 pieces, not {}: {}".format(chess.popcount(board.occupied), board.fen()))
# KvK is a draw.
if board.occupied == board.kings:
return 0
# Prepare the tablebase request.
white_squares = list(chess.SquareSet(board.occupied_co[chess.WHITE]))
white_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in white_squares]
black_squares = list(chess.SquareSet(board.occupied_co[chess.BLACK]))
black_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in black_squares]
side = 0 if (board.turn == chess.WHITE) else 1
epsq = board.ep_square if board.ep_square else NOSQUARE
req = Request(white_squares, white_types, black_squares, black_types, side, epsq)
# Probe.
dtm = self.egtb_get_dtm(req)
ply, res = unpackdist(dtm)
if res == iWMATE:
# White mates in the stored position.
if req.realside == 1:
if req.is_reversed:
return ply
else:
return -ply
else:
if req.is_reversed:
return -ply
else:
return ply
elif res == iBMATE:
# Black mates in the stored position.
if req.realside == 0:
if req.is_reversed:
return ply
else:
return -ply
else:
if req.is_reversed:
return -ply
else:
return ply
else:
# Draw.
return 0 | python | def probe_dtm(self, board: chess.Board) -> int:
"""
Probes for depth to mate information.
The absolute value is the number of half-moves until forced mate
(or ``0`` in drawn positions). The value is positive if the
side to move is winning, otherwise it is negative.
In the example position white to move will get mated in 10 half-moves:
>>> import chess
>>> import chess.gaviota
>>>
>>> with chess.gaviota.open_tablebase("data/gaviota") as tablebase:
... board = chess.Board("8/8/8/8/8/8/8/K2kr3 w - - 0 1")
... print(tablebase.probe_dtm(board))
...
-10
:raises: :exc:`KeyError` (or specifically
:exc:`chess.gaviota.MissingTableError`) if the probe fails. Use
:func:`~chess.gaviota.PythonTablebase.get_dtm()` if you prefer
to get ``None`` instead of an exception.
Note that probing a corrupted table file is undefined behavior.
"""
# Can not probe positions with castling rights.
if board.castling_rights:
raise KeyError("gaviota tables do not contain positions with castling rights: {}".format(board.fen()))
# Supports only up to 5 pieces.
if chess.popcount(board.occupied) > 5:
raise KeyError("gaviota tables support up to 5 pieces, not {}: {}".format(chess.popcount(board.occupied), board.fen()))
# KvK is a draw.
if board.occupied == board.kings:
return 0
# Prepare the tablebase request.
white_squares = list(chess.SquareSet(board.occupied_co[chess.WHITE]))
white_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in white_squares]
black_squares = list(chess.SquareSet(board.occupied_co[chess.BLACK]))
black_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in black_squares]
side = 0 if (board.turn == chess.WHITE) else 1
epsq = board.ep_square if board.ep_square else NOSQUARE
req = Request(white_squares, white_types, black_squares, black_types, side, epsq)
# Probe.
dtm = self.egtb_get_dtm(req)
ply, res = unpackdist(dtm)
if res == iWMATE:
# White mates in the stored position.
if req.realside == 1:
if req.is_reversed:
return ply
else:
return -ply
else:
if req.is_reversed:
return -ply
else:
return ply
elif res == iBMATE:
# Black mates in the stored position.
if req.realside == 0:
if req.is_reversed:
return ply
else:
return -ply
else:
if req.is_reversed:
return -ply
else:
return ply
else:
# Draw.
return 0 | [
"def",
"probe_dtm",
"(",
"self",
",",
"board",
":",
"chess",
".",
"Board",
")",
"->",
"int",
":",
"# Can not probe positions with castling rights.",
"if",
"board",
".",
"castling_rights",
":",
"raise",
"KeyError",
"(",
"\"gaviota tables do not contain positions with cas... | Probes for depth to mate information.
The absolute value is the number of half-moves until forced mate
(or ``0`` in drawn positions). The value is positive if the
side to move is winning, otherwise it is negative.
In the example position white to move will get mated in 10 half-moves:
>>> import chess
>>> import chess.gaviota
>>>
>>> with chess.gaviota.open_tablebase("data/gaviota") as tablebase:
... board = chess.Board("8/8/8/8/8/8/8/K2kr3 w - - 0 1")
... print(tablebase.probe_dtm(board))
...
-10
:raises: :exc:`KeyError` (or specifically
:exc:`chess.gaviota.MissingTableError`) if the probe fails. Use
:func:`~chess.gaviota.PythonTablebase.get_dtm()` if you prefer
to get ``None`` instead of an exception.
Note that probing a corrupted table file is undefined behavior. | [
"Probes",
"for",
"depth",
"to",
"mate",
"information",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/gaviota.py#L1556-L1633 | train | 219,720 |
niklasf/python-chess | chess/__init__.py | Piece.symbol | def symbol(self) -> str:
"""
Gets the symbol ``P``, ``N``, ``B``, ``R``, ``Q`` or ``K`` for white
pieces or the lower-case variants for the black pieces.
"""
symbol = piece_symbol(self.piece_type)
return symbol.upper() if self.color else symbol | python | def symbol(self) -> str:
"""
Gets the symbol ``P``, ``N``, ``B``, ``R``, ``Q`` or ``K`` for white
pieces or the lower-case variants for the black pieces.
"""
symbol = piece_symbol(self.piece_type)
return symbol.upper() if self.color else symbol | [
"def",
"symbol",
"(",
"self",
")",
"->",
"str",
":",
"symbol",
"=",
"piece_symbol",
"(",
"self",
".",
"piece_type",
")",
"return",
"symbol",
".",
"upper",
"(",
")",
"if",
"self",
".",
"color",
"else",
"symbol"
] | Gets the symbol ``P``, ``N``, ``B``, ``R``, ``Q`` or ``K`` for white
pieces or the lower-case variants for the black pieces. | [
"Gets",
"the",
"symbol",
"P",
"N",
"B",
"R",
"Q",
"or",
"K",
"for",
"white",
"pieces",
"or",
"the",
"lower",
"-",
"case",
"variants",
"for",
"the",
"black",
"pieces",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L394-L400 | train | 219,721 |
niklasf/python-chess | chess/__init__.py | Piece.unicode_symbol | def unicode_symbol(self, *, invert_color: bool = False) -> str:
"""
Gets the Unicode character for the piece.
"""
symbol = self.symbol().swapcase() if invert_color else self.symbol()
return UNICODE_PIECE_SYMBOLS[symbol] | python | def unicode_symbol(self, *, invert_color: bool = False) -> str:
"""
Gets the Unicode character for the piece.
"""
symbol = self.symbol().swapcase() if invert_color else self.symbol()
return UNICODE_PIECE_SYMBOLS[symbol] | [
"def",
"unicode_symbol",
"(",
"self",
",",
"*",
",",
"invert_color",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"symbol",
"=",
"self",
".",
"symbol",
"(",
")",
".",
"swapcase",
"(",
")",
"if",
"invert_color",
"else",
"self",
".",
"symbol",
"("... | Gets the Unicode character for the piece. | [
"Gets",
"the",
"Unicode",
"character",
"for",
"the",
"piece",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L402-L407 | train | 219,722 |
niklasf/python-chess | chess/__init__.py | Move.uci | def uci(self) -> str:
"""
Gets an UCI string for the move.
For example, a move from a7 to a8 would be ``a7a8`` or ``a7a8q``
(if the latter is a promotion to a queen).
The UCI representation of a null move is ``0000``.
"""
if self.drop:
return piece_symbol(self.drop).upper() + "@" + SQUARE_NAMES[self.to_square]
elif self.promotion:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square] + piece_symbol(self.promotion)
elif self:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square]
else:
return "0000" | python | def uci(self) -> str:
"""
Gets an UCI string for the move.
For example, a move from a7 to a8 would be ``a7a8`` or ``a7a8q``
(if the latter is a promotion to a queen).
The UCI representation of a null move is ``0000``.
"""
if self.drop:
return piece_symbol(self.drop).upper() + "@" + SQUARE_NAMES[self.to_square]
elif self.promotion:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square] + piece_symbol(self.promotion)
elif self:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square]
else:
return "0000" | [
"def",
"uci",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"drop",
":",
"return",
"piece_symbol",
"(",
"self",
".",
"drop",
")",
".",
"upper",
"(",
")",
"+",
"\"@\"",
"+",
"SQUARE_NAMES",
"[",
"self",
".",
"to_square",
"]",
"elif",
"self"... | Gets an UCI string for the move.
For example, a move from a7 to a8 would be ``a7a8`` or ``a7a8q``
(if the latter is a promotion to a queen).
The UCI representation of a null move is ``0000``. | [
"Gets",
"an",
"UCI",
"string",
"for",
"the",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L452-L468 | train | 219,723 |
niklasf/python-chess | chess/__init__.py | Move.from_uci | def from_uci(cls, uci: str) -> "Move":
"""
Parses an UCI string.
:raises: :exc:`ValueError` if the UCI string is invalid.
"""
if uci == "0000":
return cls.null()
elif len(uci) == 4 and "@" == uci[1]:
drop = PIECE_SYMBOLS.index(uci[0].lower())
square = SQUARE_NAMES.index(uci[2:])
return cls(square, square, drop=drop)
elif len(uci) == 4:
return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]))
elif len(uci) == 5:
promotion = PIECE_SYMBOLS.index(uci[4])
return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]), promotion=promotion)
else:
raise ValueError("expected uci string to be of length 4 or 5: {!r}".format(uci)) | python | def from_uci(cls, uci: str) -> "Move":
"""
Parses an UCI string.
:raises: :exc:`ValueError` if the UCI string is invalid.
"""
if uci == "0000":
return cls.null()
elif len(uci) == 4 and "@" == uci[1]:
drop = PIECE_SYMBOLS.index(uci[0].lower())
square = SQUARE_NAMES.index(uci[2:])
return cls(square, square, drop=drop)
elif len(uci) == 4:
return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]))
elif len(uci) == 5:
promotion = PIECE_SYMBOLS.index(uci[4])
return cls(SQUARE_NAMES.index(uci[0:2]), SQUARE_NAMES.index(uci[2:4]), promotion=promotion)
else:
raise ValueError("expected uci string to be of length 4 or 5: {!r}".format(uci)) | [
"def",
"from_uci",
"(",
"cls",
",",
"uci",
":",
"str",
")",
"->",
"\"Move\"",
":",
"if",
"uci",
"==",
"\"0000\"",
":",
"return",
"cls",
".",
"null",
"(",
")",
"elif",
"len",
"(",
"uci",
")",
"==",
"4",
"and",
"\"@\"",
"==",
"uci",
"[",
"1",
"]"... | Parses an UCI string.
:raises: :exc:`ValueError` if the UCI string is invalid. | [
"Parses",
"an",
"UCI",
"string",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L504-L522 | train | 219,724 |
niklasf/python-chess | chess/__init__.py | BaseBoard.pieces | def pieces(self, piece_type: PieceType, color: Color) -> "SquareSet":
"""
Gets pieces of the given type and color.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.pieces_mask(piece_type, color)) | python | def pieces(self, piece_type: PieceType, color: Color) -> "SquareSet":
"""
Gets pieces of the given type and color.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.pieces_mask(piece_type, color)) | [
"def",
"pieces",
"(",
"self",
",",
"piece_type",
":",
"PieceType",
",",
"color",
":",
"Color",
")",
"->",
"\"SquareSet\"",
":",
"return",
"SquareSet",
"(",
"self",
".",
"pieces_mask",
"(",
"piece_type",
",",
"color",
")",
")"
] | Gets pieces of the given type and color.
Returns a :class:`set of squares <chess.SquareSet>`. | [
"Gets",
"pieces",
"of",
"the",
"given",
"type",
"and",
"color",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L614-L620 | train | 219,725 |
niklasf/python-chess | chess/__init__.py | BaseBoard.piece_type_at | def piece_type_at(self, square: Square) -> Optional[PieceType]:
"""Gets the piece type at the given square."""
mask = BB_SQUARES[square]
if not self.occupied & mask:
return None # Early return
elif self.pawns & mask:
return PAWN
elif self.knights & mask:
return KNIGHT
elif self.bishops & mask:
return BISHOP
elif self.rooks & mask:
return ROOK
elif self.queens & mask:
return QUEEN
else:
return KING | python | def piece_type_at(self, square: Square) -> Optional[PieceType]:
"""Gets the piece type at the given square."""
mask = BB_SQUARES[square]
if not self.occupied & mask:
return None # Early return
elif self.pawns & mask:
return PAWN
elif self.knights & mask:
return KNIGHT
elif self.bishops & mask:
return BISHOP
elif self.rooks & mask:
return ROOK
elif self.queens & mask:
return QUEEN
else:
return KING | [
"def",
"piece_type_at",
"(",
"self",
",",
"square",
":",
"Square",
")",
"->",
"Optional",
"[",
"PieceType",
"]",
":",
"mask",
"=",
"BB_SQUARES",
"[",
"square",
"]",
"if",
"not",
"self",
".",
"occupied",
"&",
"mask",
":",
"return",
"None",
"# Early return... | Gets the piece type at the given square. | [
"Gets",
"the",
"piece",
"type",
"at",
"the",
"given",
"square",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L632-L649 | train | 219,726 |
niklasf/python-chess | chess/__init__.py | BaseBoard.king | def king(self, color: Color) -> Optional[Square]:
"""
Finds the king square of the given side. Returns ``None`` if there
is no king of that color.
In variants with king promotions, only non-promoted kings are
considered.
"""
king_mask = self.occupied_co[color] & self.kings & ~self.promoted
return msb(king_mask) if king_mask else None | python | def king(self, color: Color) -> Optional[Square]:
"""
Finds the king square of the given side. Returns ``None`` if there
is no king of that color.
In variants with king promotions, only non-promoted kings are
considered.
"""
king_mask = self.occupied_co[color] & self.kings & ~self.promoted
return msb(king_mask) if king_mask else None | [
"def",
"king",
"(",
"self",
",",
"color",
":",
"Color",
")",
"->",
"Optional",
"[",
"Square",
"]",
":",
"king_mask",
"=",
"self",
".",
"occupied_co",
"[",
"color",
"]",
"&",
"self",
".",
"kings",
"&",
"~",
"self",
".",
"promoted",
"return",
"msb",
... | Finds the king square of the given side. Returns ``None`` if there
is no king of that color.
In variants with king promotions, only non-promoted kings are
considered. | [
"Finds",
"the",
"king",
"square",
"of",
"the",
"given",
"side",
".",
"Returns",
"None",
"if",
"there",
"is",
"no",
"king",
"of",
"that",
"color",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L651-L660 | train | 219,727 |
niklasf/python-chess | chess/__init__.py | BaseBoard.is_attacked_by | def is_attacked_by(self, color: Color, square: Square) -> bool:
"""
Checks if the given side attacks the given square.
Pinned pieces still count as attackers. Pawns that can be captured
en passant are **not** considered attacked.
"""
return bool(self.attackers_mask(color, square)) | python | def is_attacked_by(self, color: Color, square: Square) -> bool:
"""
Checks if the given side attacks the given square.
Pinned pieces still count as attackers. Pawns that can be captured
en passant are **not** considered attacked.
"""
return bool(self.attackers_mask(color, square)) | [
"def",
"is_attacked_by",
"(",
"self",
",",
"color",
":",
"Color",
",",
"square",
":",
"Square",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"self",
".",
"attackers_mask",
"(",
"color",
",",
"square",
")",
")"
] | Checks if the given side attacks the given square.
Pinned pieces still count as attackers. Pawns that can be captured
en passant are **not** considered attacked. | [
"Checks",
"if",
"the",
"given",
"side",
"attacks",
"the",
"given",
"square",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L713-L720 | train | 219,728 |
niklasf/python-chess | chess/__init__.py | BaseBoard.attackers | def attackers(self, color: Color, square: Square) -> "SquareSet":
"""
Gets a set of attackers of the given color for the given square.
Pinned pieces still count as attackers.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.attackers_mask(color, square)) | python | def attackers(self, color: Color, square: Square) -> "SquareSet":
"""
Gets a set of attackers of the given color for the given square.
Pinned pieces still count as attackers.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.attackers_mask(color, square)) | [
"def",
"attackers",
"(",
"self",
",",
"color",
":",
"Color",
",",
"square",
":",
"Square",
")",
"->",
"\"SquareSet\"",
":",
"return",
"SquareSet",
"(",
"self",
".",
"attackers_mask",
"(",
"color",
",",
"square",
")",
")"
] | Gets a set of attackers of the given color for the given square.
Pinned pieces still count as attackers.
Returns a :class:`set of squares <chess.SquareSet>`. | [
"Gets",
"a",
"set",
"of",
"attackers",
"of",
"the",
"given",
"color",
"for",
"the",
"given",
"square",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L722-L730 | train | 219,729 |
niklasf/python-chess | chess/__init__.py | BaseBoard.is_pinned | def is_pinned(self, color: Color, square: Square) -> bool:
"""
Detects if the given square is pinned to the king of the given color.
"""
return self.pin_mask(color, square) != BB_ALL | python | def is_pinned(self, color: Color, square: Square) -> bool:
"""
Detects if the given square is pinned to the king of the given color.
"""
return self.pin_mask(color, square) != BB_ALL | [
"def",
"is_pinned",
"(",
"self",
",",
"color",
":",
"Color",
",",
"square",
":",
"Square",
")",
"->",
"bool",
":",
"return",
"self",
".",
"pin_mask",
"(",
"color",
",",
"square",
")",
"!=",
"BB_ALL"
] | Detects if the given square is pinned to the king of the given color. | [
"Detects",
"if",
"the",
"given",
"square",
"is",
"pinned",
"to",
"the",
"king",
"of",
"the",
"given",
"color",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L782-L786 | train | 219,730 |
niklasf/python-chess | chess/__init__.py | BaseBoard.set_piece_at | def set_piece_at(self, square: Square, piece: Optional[Piece], promoted: bool = False) -> None:
"""
Sets a piece at the given square.
An existing piece is replaced. Setting *piece* to ``None`` is
equivalent to :func:`~chess.Board.remove_piece_at()`.
"""
if piece is None:
self._remove_piece_at(square)
else:
self._set_piece_at(square, piece.piece_type, piece.color, promoted) | python | def set_piece_at(self, square: Square, piece: Optional[Piece], promoted: bool = False) -> None:
"""
Sets a piece at the given square.
An existing piece is replaced. Setting *piece* to ``None`` is
equivalent to :func:`~chess.Board.remove_piece_at()`.
"""
if piece is None:
self._remove_piece_at(square)
else:
self._set_piece_at(square, piece.piece_type, piece.color, promoted) | [
"def",
"set_piece_at",
"(",
"self",
",",
"square",
":",
"Square",
",",
"piece",
":",
"Optional",
"[",
"Piece",
"]",
",",
"promoted",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"if",
"piece",
"is",
"None",
":",
"self",
".",
"_remove_piece_at",
... | Sets a piece at the given square.
An existing piece is replaced. Setting *piece* to ``None`` is
equivalent to :func:`~chess.Board.remove_piece_at()`. | [
"Sets",
"a",
"piece",
"at",
"the",
"given",
"square",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L850-L860 | train | 219,731 |
niklasf/python-chess | chess/__init__.py | BaseBoard.board_fen | def board_fen(self, *, promoted: Optional[bool] = False) -> str:
"""
Gets the board FEN.
"""
builder = []
empty = 0
for square in SQUARES_180:
piece = self.piece_at(square)
if not piece:
empty += 1
else:
if empty:
builder.append(str(empty))
empty = 0
builder.append(piece.symbol())
if promoted and BB_SQUARES[square] & self.promoted:
builder.append("~")
if BB_SQUARES[square] & BB_FILE_H:
if empty:
builder.append(str(empty))
empty = 0
if square != H1:
builder.append("/")
return "".join(builder) | python | def board_fen(self, *, promoted: Optional[bool] = False) -> str:
"""
Gets the board FEN.
"""
builder = []
empty = 0
for square in SQUARES_180:
piece = self.piece_at(square)
if not piece:
empty += 1
else:
if empty:
builder.append(str(empty))
empty = 0
builder.append(piece.symbol())
if promoted and BB_SQUARES[square] & self.promoted:
builder.append("~")
if BB_SQUARES[square] & BB_FILE_H:
if empty:
builder.append(str(empty))
empty = 0
if square != H1:
builder.append("/")
return "".join(builder) | [
"def",
"board_fen",
"(",
"self",
",",
"*",
",",
"promoted",
":",
"Optional",
"[",
"bool",
"]",
"=",
"False",
")",
"->",
"str",
":",
"builder",
"=",
"[",
"]",
"empty",
"=",
"0",
"for",
"square",
"in",
"SQUARES_180",
":",
"piece",
"=",
"self",
".",
... | Gets the board FEN. | [
"Gets",
"the",
"board",
"FEN",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L862-L890 | train | 219,732 |
niklasf/python-chess | chess/__init__.py | BaseBoard.chess960_pos | def chess960_pos(self) -> Optional[int]:
"""
Gets the Chess960 starting position index between 0 and 959
or ``None``.
"""
if self.occupied_co[WHITE] != BB_RANK_1 | BB_RANK_2:
return None
if self.occupied_co[BLACK] != BB_RANK_7 | BB_RANK_8:
return None
if self.pawns != BB_RANK_2 | BB_RANK_7:
return None
if self.promoted:
return None
# Piece counts.
brnqk = [self.bishops, self.rooks, self.knights, self.queens, self.kings]
if [popcount(pieces) for pieces in brnqk] != [4, 4, 4, 2, 2]:
return None
# Symmetry.
if any((BB_RANK_1 & pieces) << 56 != BB_RANK_8 & pieces for pieces in brnqk):
return None
# Algorithm from ChessX, src/database/bitboard.cpp, r2254.
x = self.bishops & (2 + 8 + 32 + 128)
if not x:
return None
bs1 = (lsb(x) - 1) // 2
cc_pos = bs1
x = self.bishops & (1 + 4 + 16 + 64)
if not x:
return None
bs2 = lsb(x) * 2
cc_pos += bs2
q = 0
qf = False
n0 = 0
n1 = 0
n0f = False
n1f = False
rf = 0
n0s = [0, 4, 7, 9]
for square in range(A1, H1 + 1):
bb = BB_SQUARES[square]
if bb & self.queens:
qf = True
elif bb & self.rooks or bb & self.kings:
if bb & self.kings:
if rf != 1:
return None
else:
rf += 1
if not qf:
q += 1
if not n0f:
n0 += 1
elif not n1f:
n1 += 1
elif bb & self.knights:
if not qf:
q += 1
if not n0f:
n0f = True
elif not n1f:
n1f = True
if n0 < 4 and n1f and qf:
cc_pos += q * 16
krn = n0s[n0] + n1
cc_pos += krn * 96
return cc_pos
else:
return None | python | def chess960_pos(self) -> Optional[int]:
"""
Gets the Chess960 starting position index between 0 and 959
or ``None``.
"""
if self.occupied_co[WHITE] != BB_RANK_1 | BB_RANK_2:
return None
if self.occupied_co[BLACK] != BB_RANK_7 | BB_RANK_8:
return None
if self.pawns != BB_RANK_2 | BB_RANK_7:
return None
if self.promoted:
return None
# Piece counts.
brnqk = [self.bishops, self.rooks, self.knights, self.queens, self.kings]
if [popcount(pieces) for pieces in brnqk] != [4, 4, 4, 2, 2]:
return None
# Symmetry.
if any((BB_RANK_1 & pieces) << 56 != BB_RANK_8 & pieces for pieces in brnqk):
return None
# Algorithm from ChessX, src/database/bitboard.cpp, r2254.
x = self.bishops & (2 + 8 + 32 + 128)
if not x:
return None
bs1 = (lsb(x) - 1) // 2
cc_pos = bs1
x = self.bishops & (1 + 4 + 16 + 64)
if not x:
return None
bs2 = lsb(x) * 2
cc_pos += bs2
q = 0
qf = False
n0 = 0
n1 = 0
n0f = False
n1f = False
rf = 0
n0s = [0, 4, 7, 9]
for square in range(A1, H1 + 1):
bb = BB_SQUARES[square]
if bb & self.queens:
qf = True
elif bb & self.rooks or bb & self.kings:
if bb & self.kings:
if rf != 1:
return None
else:
rf += 1
if not qf:
q += 1
if not n0f:
n0 += 1
elif not n1f:
n1 += 1
elif bb & self.knights:
if not qf:
q += 1
if not n0f:
n0f = True
elif not n1f:
n1f = True
if n0 < 4 and n1f and qf:
cc_pos += q * 16
krn = n0s[n0] + n1
cc_pos += krn * 96
return cc_pos
else:
return None | [
"def",
"chess960_pos",
"(",
"self",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"self",
".",
"occupied_co",
"[",
"WHITE",
"]",
"!=",
"BB_RANK_1",
"|",
"BB_RANK_2",
":",
"return",
"None",
"if",
"self",
".",
"occupied_co",
"[",
"BLACK",
"]",
"!=",... | Gets the Chess960 starting position index between 0 and 959
or ``None``. | [
"Gets",
"the",
"Chess960",
"starting",
"position",
"index",
"between",
"0",
"and",
"959",
"or",
"None",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1043-L1119 | train | 219,733 |
niklasf/python-chess | chess/__init__.py | BaseBoard.mirror | def mirror(self: BaseBoardT) -> BaseBoardT:
"""
Returns a mirrored copy of the board.
The board is mirrored vertically and piece colors are swapped, so that
the position is equivalent modulo color.
"""
board = self.transform(flip_vertical)
board.occupied_co[WHITE], board.occupied_co[BLACK] = board.occupied_co[BLACK], board.occupied_co[WHITE]
return board | python | def mirror(self: BaseBoardT) -> BaseBoardT:
"""
Returns a mirrored copy of the board.
The board is mirrored vertically and piece colors are swapped, so that
the position is equivalent modulo color.
"""
board = self.transform(flip_vertical)
board.occupied_co[WHITE], board.occupied_co[BLACK] = board.occupied_co[BLACK], board.occupied_co[WHITE]
return board | [
"def",
"mirror",
"(",
"self",
":",
"BaseBoardT",
")",
"->",
"BaseBoardT",
":",
"board",
"=",
"self",
".",
"transform",
"(",
"flip_vertical",
")",
"board",
".",
"occupied_co",
"[",
"WHITE",
"]",
",",
"board",
".",
"occupied_co",
"[",
"BLACK",
"]",
"=",
... | Returns a mirrored copy of the board.
The board is mirrored vertically and piece colors are swapped, so that
the position is equivalent modulo color. | [
"Returns",
"a",
"mirrored",
"copy",
"of",
"the",
"board",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1226-L1235 | train | 219,734 |
niklasf/python-chess | chess/__init__.py | BaseBoard.from_chess960_pos | def from_chess960_pos(cls: Type[BaseBoardT], sharnagl: int) -> BaseBoardT:
"""
Creates a new board, initialized with a Chess960 starting position.
>>> import chess
>>> import random
>>>
>>> board = chess.Board.from_chess960_pos(random.randint(0, 959))
"""
board = cls.empty()
board.set_chess960_pos(sharnagl)
return board | python | def from_chess960_pos(cls: Type[BaseBoardT], sharnagl: int) -> BaseBoardT:
"""
Creates a new board, initialized with a Chess960 starting position.
>>> import chess
>>> import random
>>>
>>> board = chess.Board.from_chess960_pos(random.randint(0, 959))
"""
board = cls.empty()
board.set_chess960_pos(sharnagl)
return board | [
"def",
"from_chess960_pos",
"(",
"cls",
":",
"Type",
"[",
"BaseBoardT",
"]",
",",
"sharnagl",
":",
"int",
")",
"->",
"BaseBoardT",
":",
"board",
"=",
"cls",
".",
"empty",
"(",
")",
"board",
".",
"set_chess960_pos",
"(",
"sharnagl",
")",
"return",
"board"... | Creates a new board, initialized with a Chess960 starting position.
>>> import chess
>>> import random
>>>
>>> board = chess.Board.from_chess960_pos(random.randint(0, 959)) | [
"Creates",
"a",
"new",
"board",
"initialized",
"with",
"a",
"Chess960",
"starting",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1272-L1283 | train | 219,735 |
niklasf/python-chess | chess/__init__.py | Board.reset | def reset(self) -> None:
"""Restores the starting position."""
self.turn = WHITE
self.castling_rights = BB_CORNERS
self.ep_square = None
self.halfmove_clock = 0
self.fullmove_number = 1
self.reset_board() | python | def reset(self) -> None:
"""Restores the starting position."""
self.turn = WHITE
self.castling_rights = BB_CORNERS
self.ep_square = None
self.halfmove_clock = 0
self.fullmove_number = 1
self.reset_board() | [
"def",
"reset",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"turn",
"=",
"WHITE",
"self",
".",
"castling_rights",
"=",
"BB_CORNERS",
"self",
".",
"ep_square",
"=",
"None",
"self",
".",
"halfmove_clock",
"=",
"0",
"self",
".",
"fullmove_number",
"="... | Restores the starting position. | [
"Restores",
"the",
"starting",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1394-L1402 | train | 219,736 |
niklasf/python-chess | chess/__init__.py | Board.clear | def clear(self) -> None:
"""
Clears the board.
Resets move stack and move counters. The side to move is white. There
are no rooks or kings, so castling rights are removed.
In order to be in a valid :func:`~chess.Board.status()` at least kings
need to be put on the board.
"""
self.turn = WHITE
self.castling_rights = BB_EMPTY
self.ep_square = None
self.halfmove_clock = 0
self.fullmove_number = 1
self.clear_board() | python | def clear(self) -> None:
"""
Clears the board.
Resets move stack and move counters. The side to move is white. There
are no rooks or kings, so castling rights are removed.
In order to be in a valid :func:`~chess.Board.status()` at least kings
need to be put on the board.
"""
self.turn = WHITE
self.castling_rights = BB_EMPTY
self.ep_square = None
self.halfmove_clock = 0
self.fullmove_number = 1
self.clear_board() | [
"def",
"clear",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"turn",
"=",
"WHITE",
"self",
".",
"castling_rights",
"=",
"BB_EMPTY",
"self",
".",
"ep_square",
"=",
"None",
"self",
".",
"halfmove_clock",
"=",
"0",
"self",
".",
"fullmove_number",
"=",
... | Clears the board.
Resets move stack and move counters. The side to move is white. There
are no rooks or kings, so castling rights are removed.
In order to be in a valid :func:`~chess.Board.status()` at least kings
need to be put on the board. | [
"Clears",
"the",
"board",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1408-L1424 | train | 219,737 |
niklasf/python-chess | chess/__init__.py | Board.root | def root(self: BoardT) -> BoardT:
"""Returns a copy of the root position."""
if self._stack:
board = type(self)(None, chess960=self.chess960)
self._stack[0].restore(board)
return board
else:
return self.copy(stack=False) | python | def root(self: BoardT) -> BoardT:
"""Returns a copy of the root position."""
if self._stack:
board = type(self)(None, chess960=self.chess960)
self._stack[0].restore(board)
return board
else:
return self.copy(stack=False) | [
"def",
"root",
"(",
"self",
":",
"BoardT",
")",
"->",
"BoardT",
":",
"if",
"self",
".",
"_stack",
":",
"board",
"=",
"type",
"(",
"self",
")",
"(",
"None",
",",
"chess960",
"=",
"self",
".",
"chess960",
")",
"self",
".",
"_stack",
"[",
"0",
"]",
... | Returns a copy of the root position. | [
"Returns",
"a",
"copy",
"of",
"the",
"root",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1435-L1442 | train | 219,738 |
niklasf/python-chess | chess/__init__.py | Board.is_check | def is_check(self) -> bool:
"""Returns if the current side to move is in check."""
king = self.king(self.turn)
return king is not None and self.is_attacked_by(not self.turn, king) | python | def is_check(self) -> bool:
"""Returns if the current side to move is in check."""
king = self.king(self.turn)
return king is not None and self.is_attacked_by(not self.turn, king) | [
"def",
"is_check",
"(",
"self",
")",
"->",
"bool",
":",
"king",
"=",
"self",
".",
"king",
"(",
"self",
".",
"turn",
")",
"return",
"king",
"is",
"not",
"None",
"and",
"self",
".",
"is_attacked_by",
"(",
"not",
"self",
".",
"turn",
",",
"king",
")"
... | Returns if the current side to move is in check. | [
"Returns",
"if",
"the",
"current",
"side",
"to",
"move",
"is",
"in",
"check",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1540-L1543 | train | 219,739 |
niklasf/python-chess | chess/__init__.py | Board.is_into_check | def is_into_check(self, move: Move) -> bool:
"""
Checks if the given move would leave the king in check or put it into
check. The move must be at least pseudo legal.
"""
king = self.king(self.turn)
if king is None:
return False
checkers = self.attackers_mask(not self.turn, king)
if checkers:
# If already in check, look if it is an evasion.
if move not in self._generate_evasions(king, checkers, BB_SQUARES[move.from_square], BB_SQUARES[move.to_square]):
return True
return not self._is_safe(king, self._slider_blockers(king), move) | python | def is_into_check(self, move: Move) -> bool:
"""
Checks if the given move would leave the king in check or put it into
check. The move must be at least pseudo legal.
"""
king = self.king(self.turn)
if king is None:
return False
checkers = self.attackers_mask(not self.turn, king)
if checkers:
# If already in check, look if it is an evasion.
if move not in self._generate_evasions(king, checkers, BB_SQUARES[move.from_square], BB_SQUARES[move.to_square]):
return True
return not self._is_safe(king, self._slider_blockers(king), move) | [
"def",
"is_into_check",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"king",
"=",
"self",
".",
"king",
"(",
"self",
".",
"turn",
")",
"if",
"king",
"is",
"None",
":",
"return",
"False",
"checkers",
"=",
"self",
".",
"attackers_mask"... | Checks if the given move would leave the king in check or put it into
check. The move must be at least pseudo legal. | [
"Checks",
"if",
"the",
"given",
"move",
"would",
"leave",
"the",
"king",
"in",
"check",
"or",
"put",
"it",
"into",
"check",
".",
"The",
"move",
"must",
"be",
"at",
"least",
"pseudo",
"legal",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1545-L1560 | train | 219,740 |
niklasf/python-chess | chess/__init__.py | Board.was_into_check | def was_into_check(self) -> bool:
"""
Checks if the king of the other side is attacked. Such a position is not
valid and could only be reached by an illegal move.
"""
king = self.king(not self.turn)
return king is not None and self.is_attacked_by(self.turn, king) | python | def was_into_check(self) -> bool:
"""
Checks if the king of the other side is attacked. Such a position is not
valid and could only be reached by an illegal move.
"""
king = self.king(not self.turn)
return king is not None and self.is_attacked_by(self.turn, king) | [
"def",
"was_into_check",
"(",
"self",
")",
"->",
"bool",
":",
"king",
"=",
"self",
".",
"king",
"(",
"not",
"self",
".",
"turn",
")",
"return",
"king",
"is",
"not",
"None",
"and",
"self",
".",
"is_attacked_by",
"(",
"self",
".",
"turn",
",",
"king",
... | Checks if the king of the other side is attacked. Such a position is not
valid and could only be reached by an illegal move. | [
"Checks",
"if",
"the",
"king",
"of",
"the",
"other",
"side",
"is",
"attacked",
".",
"Such",
"a",
"position",
"is",
"not",
"valid",
"and",
"could",
"only",
"be",
"reached",
"by",
"an",
"illegal",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1562-L1568 | train | 219,741 |
niklasf/python-chess | chess/__init__.py | Board.result | def result(self, *, claim_draw: bool = False) -> str:
"""
Gets the game result.
``1-0``, ``0-1`` or ``1/2-1/2`` if the
:func:`game is over <chess.Board.is_game_over()>`. Otherwise, the
result is undetermined: ``*``.
"""
# Chess variant support.
if self.is_variant_loss():
return "0-1" if self.turn == WHITE else "1-0"
elif self.is_variant_win():
return "1-0" if self.turn == WHITE else "0-1"
elif self.is_variant_draw():
return "1/2-1/2"
# Checkmate.
if self.is_checkmate():
return "0-1" if self.turn == WHITE else "1-0"
# Draw claimed.
if claim_draw and self.can_claim_draw():
return "1/2-1/2"
# Seventyfive-move rule or fivefold repetition.
if self.is_seventyfive_moves() or self.is_fivefold_repetition():
return "1/2-1/2"
# Insufficient material.
if self.is_insufficient_material():
return "1/2-1/2"
# Stalemate.
if not any(self.generate_legal_moves()):
return "1/2-1/2"
# Undetermined.
return "*" | python | def result(self, *, claim_draw: bool = False) -> str:
"""
Gets the game result.
``1-0``, ``0-1`` or ``1/2-1/2`` if the
:func:`game is over <chess.Board.is_game_over()>`. Otherwise, the
result is undetermined: ``*``.
"""
# Chess variant support.
if self.is_variant_loss():
return "0-1" if self.turn == WHITE else "1-0"
elif self.is_variant_win():
return "1-0" if self.turn == WHITE else "0-1"
elif self.is_variant_draw():
return "1/2-1/2"
# Checkmate.
if self.is_checkmate():
return "0-1" if self.turn == WHITE else "1-0"
# Draw claimed.
if claim_draw and self.can_claim_draw():
return "1/2-1/2"
# Seventyfive-move rule or fivefold repetition.
if self.is_seventyfive_moves() or self.is_fivefold_repetition():
return "1/2-1/2"
# Insufficient material.
if self.is_insufficient_material():
return "1/2-1/2"
# Stalemate.
if not any(self.generate_legal_moves()):
return "1/2-1/2"
# Undetermined.
return "*" | [
"def",
"result",
"(",
"self",
",",
"*",
",",
"claim_draw",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"# Chess variant support.",
"if",
"self",
".",
"is_variant_loss",
"(",
")",
":",
"return",
"\"0-1\"",
"if",
"self",
".",
"turn",
"==",
"WHITE",
... | Gets the game result.
``1-0``, ``0-1`` or ``1/2-1/2`` if the
:func:`game is over <chess.Board.is_game_over()>`. Otherwise, the
result is undetermined: ``*``. | [
"Gets",
"the",
"game",
"result",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1686-L1723 | train | 219,742 |
niklasf/python-chess | chess/__init__.py | Board.is_stalemate | def is_stalemate(self) -> bool:
"""Checks if the current position is a stalemate."""
if self.is_check():
return False
if self.is_variant_end():
return False
return not any(self.generate_legal_moves()) | python | def is_stalemate(self) -> bool:
"""Checks if the current position is a stalemate."""
if self.is_check():
return False
if self.is_variant_end():
return False
return not any(self.generate_legal_moves()) | [
"def",
"is_stalemate",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"is_check",
"(",
")",
":",
"return",
"False",
"if",
"self",
".",
"is_variant_end",
"(",
")",
":",
"return",
"False",
"return",
"not",
"any",
"(",
"self",
".",
"generate_lega... | Checks if the current position is a stalemate. | [
"Checks",
"if",
"the",
"current",
"position",
"is",
"a",
"stalemate",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1732-L1740 | train | 219,743 |
niklasf/python-chess | chess/__init__.py | Board.can_claim_fifty_moves | def can_claim_fifty_moves(self) -> bool:
"""
Draw by the fifty-move rule can be claimed once the clock of halfmoves
since the last capture or pawn move becomes equal or greater to 100
and the side to move still has a legal move they can make.
"""
# Fifty-move rule.
if self.halfmove_clock >= 100:
if any(self.generate_legal_moves()):
return True
return False | python | def can_claim_fifty_moves(self) -> bool:
"""
Draw by the fifty-move rule can be claimed once the clock of halfmoves
since the last capture or pawn move becomes equal or greater to 100
and the side to move still has a legal move they can make.
"""
# Fifty-move rule.
if self.halfmove_clock >= 100:
if any(self.generate_legal_moves()):
return True
return False | [
"def",
"can_claim_fifty_moves",
"(",
"self",
")",
"->",
"bool",
":",
"# Fifty-move rule.",
"if",
"self",
".",
"halfmove_clock",
">=",
"100",
":",
"if",
"any",
"(",
"self",
".",
"generate_legal_moves",
"(",
")",
")",
":",
"return",
"True",
"return",
"False"
] | Draw by the fifty-move rule can be claimed once the clock of halfmoves
since the last capture or pawn move becomes equal or greater to 100
and the side to move still has a legal move they can make. | [
"Draw",
"by",
"the",
"fifty",
"-",
"move",
"rule",
"can",
"be",
"claimed",
"once",
"the",
"clock",
"of",
"halfmoves",
"since",
"the",
"last",
"capture",
"or",
"pawn",
"move",
"becomes",
"equal",
"or",
"greater",
"to",
"100",
"and",
"the",
"side",
"to",
... | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1832-L1843 | train | 219,744 |
niklasf/python-chess | chess/__init__.py | Board.can_claim_threefold_repetition | def can_claim_threefold_repetition(self) -> bool:
"""
Draw by threefold repetition can be claimed if the position on the
board occured for the third time or if such a repetition is reached
with one of the possible legal moves.
Note that checking this can be slow: In the worst case
scenario every legal move has to be tested and the entire game has to
be replayed because there is no incremental transposition table.
"""
transposition_key = self._transposition_key()
transpositions = collections.Counter() # type: typing.Counter[Hashable]
transpositions.update((transposition_key, ))
# Count positions.
switchyard = []
while self.move_stack:
move = self.pop()
switchyard.append(move)
if self.is_irreversible(move):
break
transpositions.update((self._transposition_key(), ))
while switchyard:
self.push(switchyard.pop())
# Threefold repetition occured.
if transpositions[transposition_key] >= 3:
return True
# The next legal move is a threefold repetition.
for move in self.generate_legal_moves():
self.push(move)
try:
if transpositions[self._transposition_key()] >= 2:
return True
finally:
self.pop()
return False | python | def can_claim_threefold_repetition(self) -> bool:
"""
Draw by threefold repetition can be claimed if the position on the
board occured for the third time or if such a repetition is reached
with one of the possible legal moves.
Note that checking this can be slow: In the worst case
scenario every legal move has to be tested and the entire game has to
be replayed because there is no incremental transposition table.
"""
transposition_key = self._transposition_key()
transpositions = collections.Counter() # type: typing.Counter[Hashable]
transpositions.update((transposition_key, ))
# Count positions.
switchyard = []
while self.move_stack:
move = self.pop()
switchyard.append(move)
if self.is_irreversible(move):
break
transpositions.update((self._transposition_key(), ))
while switchyard:
self.push(switchyard.pop())
# Threefold repetition occured.
if transpositions[transposition_key] >= 3:
return True
# The next legal move is a threefold repetition.
for move in self.generate_legal_moves():
self.push(move)
try:
if transpositions[self._transposition_key()] >= 2:
return True
finally:
self.pop()
return False | [
"def",
"can_claim_threefold_repetition",
"(",
"self",
")",
"->",
"bool",
":",
"transposition_key",
"=",
"self",
".",
"_transposition_key",
"(",
")",
"transpositions",
"=",
"collections",
".",
"Counter",
"(",
")",
"# type: typing.Counter[Hashable]",
"transpositions",
"... | Draw by threefold repetition can be claimed if the position on the
board occured for the third time or if such a repetition is reached
with one of the possible legal moves.
Note that checking this can be slow: In the worst case
scenario every legal move has to be tested and the entire game has to
be replayed because there is no incremental transposition table. | [
"Draw",
"by",
"threefold",
"repetition",
"can",
"be",
"claimed",
"if",
"the",
"position",
"on",
"the",
"board",
"occured",
"for",
"the",
"third",
"time",
"or",
"if",
"such",
"a",
"repetition",
"is",
"reached",
"with",
"one",
"of",
"the",
"possible",
"legal... | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1845-L1886 | train | 219,745 |
niklasf/python-chess | chess/__init__.py | Board.pop | def pop(self: BoardT) -> Move:
"""
Restores the previous position and returns the last move from the stack.
:raises: :exc:`IndexError` if the stack is empty.
"""
move = self.move_stack.pop()
self._stack.pop().restore(self)
return move | python | def pop(self: BoardT) -> Move:
"""
Restores the previous position and returns the last move from the stack.
:raises: :exc:`IndexError` if the stack is empty.
"""
move = self.move_stack.pop()
self._stack.pop().restore(self)
return move | [
"def",
"pop",
"(",
"self",
":",
"BoardT",
")",
"->",
"Move",
":",
"move",
"=",
"self",
".",
"move_stack",
".",
"pop",
"(",
")",
"self",
".",
"_stack",
".",
"pop",
"(",
")",
".",
"restore",
"(",
"self",
")",
"return",
"move"
] | Restores the previous position and returns the last move from the stack.
:raises: :exc:`IndexError` if the stack is empty. | [
"Restores",
"the",
"previous",
"position",
"and",
"returns",
"the",
"last",
"move",
"from",
"the",
"stack",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2048-L2056 | train | 219,746 |
niklasf/python-chess | chess/__init__.py | Board.fen | def fen(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None) -> str:
"""
Gets a FEN representation of the position.
A FEN string (e.g.,
``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``) consists
of the position part :func:`~chess.Board.board_fen()`, the
:data:`~chess.Board.turn`, the castling part
(:data:`~chess.Board.castling_rights`),
the en passant square (:data:`~chess.Board.ep_square`),
the :data:`~chess.Board.halfmove_clock`
and the :data:`~chess.Board.fullmove_number`.
:param shredder: Use :func:`~chess.Board.castling_shredder_fen()`
and encode castling rights by the file of the rook
(like ``HAha``) instead of the default
:func:`~chess.Board.castling_xfen()` (like ``KQkq``).
:param en_passant: By default, only fully legal en passant squares
are included (:func:`~chess.Board.has_legal_en_passant()`).
Pass ``fen`` to strictly follow the FEN specification
(always include the en passant square after a two-step pawn move)
or ``xfen`` to follow the X-FEN specification
(:func:`~chess.Board.has_pseudo_legal_en_passant()`).
:param promoted: Mark promoted pieces like ``Q~``. By default, this is
only enabled in chess variants where this is relevant.
"""
return " ".join([
self.epd(shredder=shredder, en_passant=en_passant, promoted=promoted),
str(self.halfmove_clock),
str(self.fullmove_number)
]) | python | def fen(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None) -> str:
"""
Gets a FEN representation of the position.
A FEN string (e.g.,
``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``) consists
of the position part :func:`~chess.Board.board_fen()`, the
:data:`~chess.Board.turn`, the castling part
(:data:`~chess.Board.castling_rights`),
the en passant square (:data:`~chess.Board.ep_square`),
the :data:`~chess.Board.halfmove_clock`
and the :data:`~chess.Board.fullmove_number`.
:param shredder: Use :func:`~chess.Board.castling_shredder_fen()`
and encode castling rights by the file of the rook
(like ``HAha``) instead of the default
:func:`~chess.Board.castling_xfen()` (like ``KQkq``).
:param en_passant: By default, only fully legal en passant squares
are included (:func:`~chess.Board.has_legal_en_passant()`).
Pass ``fen`` to strictly follow the FEN specification
(always include the en passant square after a two-step pawn move)
or ``xfen`` to follow the X-FEN specification
(:func:`~chess.Board.has_pseudo_legal_en_passant()`).
:param promoted: Mark promoted pieces like ``Q~``. By default, this is
only enabled in chess variants where this is relevant.
"""
return " ".join([
self.epd(shredder=shredder, en_passant=en_passant, promoted=promoted),
str(self.halfmove_clock),
str(self.fullmove_number)
]) | [
"def",
"fen",
"(",
"self",
",",
"*",
",",
"shredder",
":",
"bool",
"=",
"False",
",",
"en_passant",
":",
"str",
"=",
"\"legal\"",
",",
"promoted",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
")",
"->",
"str",
":",
"return",
"\" \"",
".",
"join"... | Gets a FEN representation of the position.
A FEN string (e.g.,
``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``) consists
of the position part :func:`~chess.Board.board_fen()`, the
:data:`~chess.Board.turn`, the castling part
(:data:`~chess.Board.castling_rights`),
the en passant square (:data:`~chess.Board.ep_square`),
the :data:`~chess.Board.halfmove_clock`
and the :data:`~chess.Board.fullmove_number`.
:param shredder: Use :func:`~chess.Board.castling_shredder_fen()`
and encode castling rights by the file of the rook
(like ``HAha``) instead of the default
:func:`~chess.Board.castling_xfen()` (like ``KQkq``).
:param en_passant: By default, only fully legal en passant squares
are included (:func:`~chess.Board.has_legal_en_passant()`).
Pass ``fen`` to strictly follow the FEN specification
(always include the en passant square after a two-step pawn move)
or ``xfen`` to follow the X-FEN specification
(:func:`~chess.Board.has_pseudo_legal_en_passant()`).
:param promoted: Mark promoted pieces like ``Q~``. By default, this is
only enabled in chess variants where this is relevant. | [
"Gets",
"a",
"FEN",
"representation",
"of",
"the",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2118-L2148 | train | 219,747 |
niklasf/python-chess | chess/__init__.py | Board.set_fen | def set_fen(self, fen: str) -> None:
"""
Parses a FEN and sets the position from it.
:raises: :exc:`ValueError` if the FEN string is invalid.
"""
parts = fen.split()
# Board part.
try:
board_part = parts.pop(0)
except IndexError:
raise ValueError("empty fen")
# Turn.
try:
turn_part = parts.pop(0)
except IndexError:
turn = WHITE
else:
if turn_part == "w":
turn = WHITE
elif turn_part == "b":
turn = BLACK
else:
raise ValueError("expected 'w' or 'b' for turn part of fen: {!r}".format(fen))
# Validate castling part.
try:
castling_part = parts.pop(0)
except IndexError:
castling_part = "-"
else:
if not FEN_CASTLING_REGEX.match(castling_part):
raise ValueError("invalid castling part in fen: {!r}".format(fen))
# En passant square.
try:
ep_part = parts.pop(0)
except IndexError:
ep_square = None
else:
try:
ep_square = None if ep_part == "-" else SQUARE_NAMES.index(ep_part)
except ValueError:
raise ValueError("invalid en passant part in fen: {!r}".format(fen))
# Check that the half-move part is valid.
try:
halfmove_part = parts.pop(0)
except IndexError:
halfmove_clock = 0
else:
try:
halfmove_clock = int(halfmove_part)
except ValueError:
raise ValueError("invalid half-move clock in fen: {!r}".format(fen))
if halfmove_clock < 0:
raise ValueError("half-move clock cannot be negative: {!r}".format(fen))
# Check that the full-move number part is valid.
# 0 is allowed for compability, but later replaced with 1.
try:
fullmove_part = parts.pop(0)
except IndexError:
fullmove_number = 1
else:
try:
fullmove_number = int(fullmove_part)
except ValueError:
raise ValueError("invalid fullmove number in fen: {!r}".format(fen))
if fullmove_number < 0:
raise ValueError("fullmove number cannot be negative: {!r}".format(fen))
fullmove_number = max(fullmove_number, 1)
# All parts should be consumed now.
if parts:
raise ValueError("fen string has more parts than expected: {!r}".format(fen))
# Validate the board part and set it.
self._set_board_fen(board_part)
# Apply.
self.turn = turn
self._set_castling_fen(castling_part)
self.ep_square = ep_square
self.halfmove_clock = halfmove_clock
self.fullmove_number = fullmove_number
self.clear_stack() | python | def set_fen(self, fen: str) -> None:
"""
Parses a FEN and sets the position from it.
:raises: :exc:`ValueError` if the FEN string is invalid.
"""
parts = fen.split()
# Board part.
try:
board_part = parts.pop(0)
except IndexError:
raise ValueError("empty fen")
# Turn.
try:
turn_part = parts.pop(0)
except IndexError:
turn = WHITE
else:
if turn_part == "w":
turn = WHITE
elif turn_part == "b":
turn = BLACK
else:
raise ValueError("expected 'w' or 'b' for turn part of fen: {!r}".format(fen))
# Validate castling part.
try:
castling_part = parts.pop(0)
except IndexError:
castling_part = "-"
else:
if not FEN_CASTLING_REGEX.match(castling_part):
raise ValueError("invalid castling part in fen: {!r}".format(fen))
# En passant square.
try:
ep_part = parts.pop(0)
except IndexError:
ep_square = None
else:
try:
ep_square = None if ep_part == "-" else SQUARE_NAMES.index(ep_part)
except ValueError:
raise ValueError("invalid en passant part in fen: {!r}".format(fen))
# Check that the half-move part is valid.
try:
halfmove_part = parts.pop(0)
except IndexError:
halfmove_clock = 0
else:
try:
halfmove_clock = int(halfmove_part)
except ValueError:
raise ValueError("invalid half-move clock in fen: {!r}".format(fen))
if halfmove_clock < 0:
raise ValueError("half-move clock cannot be negative: {!r}".format(fen))
# Check that the full-move number part is valid.
# 0 is allowed for compability, but later replaced with 1.
try:
fullmove_part = parts.pop(0)
except IndexError:
fullmove_number = 1
else:
try:
fullmove_number = int(fullmove_part)
except ValueError:
raise ValueError("invalid fullmove number in fen: {!r}".format(fen))
if fullmove_number < 0:
raise ValueError("fullmove number cannot be negative: {!r}".format(fen))
fullmove_number = max(fullmove_number, 1)
# All parts should be consumed now.
if parts:
raise ValueError("fen string has more parts than expected: {!r}".format(fen))
# Validate the board part and set it.
self._set_board_fen(board_part)
# Apply.
self.turn = turn
self._set_castling_fen(castling_part)
self.ep_square = ep_square
self.halfmove_clock = halfmove_clock
self.fullmove_number = fullmove_number
self.clear_stack() | [
"def",
"set_fen",
"(",
"self",
",",
"fen",
":",
"str",
")",
"->",
"None",
":",
"parts",
"=",
"fen",
".",
"split",
"(",
")",
"# Board part.",
"try",
":",
"board_part",
"=",
"parts",
".",
"pop",
"(",
"0",
")",
"except",
"IndexError",
":",
"raise",
"V... | Parses a FEN and sets the position from it.
:raises: :exc:`ValueError` if the FEN string is invalid. | [
"Parses",
"a",
"FEN",
"and",
"sets",
"the",
"position",
"from",
"it",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2157-L2248 | train | 219,748 |
niklasf/python-chess | chess/__init__.py | Board.chess960_pos | def chess960_pos(self, *, ignore_turn: bool = False, ignore_castling: bool = False, ignore_counters: bool = True) -> Optional[int]:
"""
Gets the Chess960 starting position index between 0 and 956
or ``None`` if the current position is not a Chess960 starting
position.
By default white to move (**ignore_turn**) and full castling rights
(**ignore_castling**) are required, but move counters
(**ignore_counters**) are ignored.
"""
if self.ep_square:
return None
if not ignore_turn:
if self.turn != WHITE:
return None
if not ignore_castling:
if self.clean_castling_rights() != self.rooks:
return None
if not ignore_counters:
if self.fullmove_number != 1 or self.halfmove_clock != 0:
return None
return super().chess960_pos() | python | def chess960_pos(self, *, ignore_turn: bool = False, ignore_castling: bool = False, ignore_counters: bool = True) -> Optional[int]:
"""
Gets the Chess960 starting position index between 0 and 956
or ``None`` if the current position is not a Chess960 starting
position.
By default white to move (**ignore_turn**) and full castling rights
(**ignore_castling**) are required, but move counters
(**ignore_counters**) are ignored.
"""
if self.ep_square:
return None
if not ignore_turn:
if self.turn != WHITE:
return None
if not ignore_castling:
if self.clean_castling_rights() != self.rooks:
return None
if not ignore_counters:
if self.fullmove_number != 1 or self.halfmove_clock != 0:
return None
return super().chess960_pos() | [
"def",
"chess960_pos",
"(",
"self",
",",
"*",
",",
"ignore_turn",
":",
"bool",
"=",
"False",
",",
"ignore_castling",
":",
"bool",
"=",
"False",
",",
"ignore_counters",
":",
"bool",
"=",
"True",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"self",... | Gets the Chess960 starting position index between 0 and 956
or ``None`` if the current position is not a Chess960 starting
position.
By default white to move (**ignore_turn**) and full castling rights
(**ignore_castling**) are required, but move counters
(**ignore_counters**) are ignored. | [
"Gets",
"the",
"Chess960",
"starting",
"position",
"index",
"between",
"0",
"and",
"956",
"or",
"None",
"if",
"the",
"current",
"position",
"is",
"not",
"a",
"Chess960",
"starting",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2312-L2337 | train | 219,749 |
niklasf/python-chess | chess/__init__.py | Board.epd | def epd(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None, **operations: Union[None, str, int, float, Move, Iterable[Move]]) -> str:
"""
Gets an EPD representation of the current position.
See :func:`~chess.Board.fen()` for FEN formatting options (*shredder*,
*ep_square* and *promoted*).
EPD operations can be given as keyword arguments. Supported operands
are strings, integers, floats, moves, lists of moves and ``None``.
All other operands are converted to strings.
A list of moves for *pv* will be interpreted as a variation. All other
move lists are interpreted as a set of moves in the current position.
*hmvc* and *fmvc* are not included by default. You can use:
>>> import chess
>>>
>>> board = chess.Board()
>>> board.epd(hmvc=board.halfmove_clock, fmvc=board.fullmove_number)
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - hmvc 0; fmvc 1;'
"""
if en_passant == "fen":
ep_square = self.ep_square
elif en_passant == "xfen":
ep_square = self.ep_square if self.has_pseudo_legal_en_passant() else None
else:
ep_square = self.ep_square if self.has_legal_en_passant() else None
epd = [self.board_fen(promoted=promoted),
"w" if self.turn == WHITE else "b",
self.castling_shredder_fen() if shredder else self.castling_xfen(),
SQUARE_NAMES[ep_square] if ep_square is not None else "-"]
if operations:
epd.append(self._epd_operations(operations))
return " ".join(epd) | python | def epd(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None, **operations: Union[None, str, int, float, Move, Iterable[Move]]) -> str:
"""
Gets an EPD representation of the current position.
See :func:`~chess.Board.fen()` for FEN formatting options (*shredder*,
*ep_square* and *promoted*).
EPD operations can be given as keyword arguments. Supported operands
are strings, integers, floats, moves, lists of moves and ``None``.
All other operands are converted to strings.
A list of moves for *pv* will be interpreted as a variation. All other
move lists are interpreted as a set of moves in the current position.
*hmvc* and *fmvc* are not included by default. You can use:
>>> import chess
>>>
>>> board = chess.Board()
>>> board.epd(hmvc=board.halfmove_clock, fmvc=board.fullmove_number)
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - hmvc 0; fmvc 1;'
"""
if en_passant == "fen":
ep_square = self.ep_square
elif en_passant == "xfen":
ep_square = self.ep_square if self.has_pseudo_legal_en_passant() else None
else:
ep_square = self.ep_square if self.has_legal_en_passant() else None
epd = [self.board_fen(promoted=promoted),
"w" if self.turn == WHITE else "b",
self.castling_shredder_fen() if shredder else self.castling_xfen(),
SQUARE_NAMES[ep_square] if ep_square is not None else "-"]
if operations:
epd.append(self._epd_operations(operations))
return " ".join(epd) | [
"def",
"epd",
"(",
"self",
",",
"*",
",",
"shredder",
":",
"bool",
"=",
"False",
",",
"en_passant",
":",
"str",
"=",
"\"legal\"",
",",
"promoted",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"*",
"*",
"operations",
":",
"Union",
"[",
"None... | Gets an EPD representation of the current position.
See :func:`~chess.Board.fen()` for FEN formatting options (*shredder*,
*ep_square* and *promoted*).
EPD operations can be given as keyword arguments. Supported operands
are strings, integers, floats, moves, lists of moves and ``None``.
All other operands are converted to strings.
A list of moves for *pv* will be interpreted as a variation. All other
move lists are interpreted as a set of moves in the current position.
*hmvc* and *fmvc* are not included by default. You can use:
>>> import chess
>>>
>>> board = chess.Board()
>>> board.epd(hmvc=board.halfmove_clock, fmvc=board.fullmove_number)
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - hmvc 0; fmvc 1;' | [
"Gets",
"an",
"EPD",
"representation",
"of",
"the",
"current",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2398-L2435 | train | 219,750 |
niklasf/python-chess | chess/__init__.py | Board.lan | def lan(self, move: Move) -> str:
"""
Gets the long algebraic notation of the given move in the context of
the current position.
"""
return self._algebraic(move, long=True) | python | def lan(self, move: Move) -> str:
"""
Gets the long algebraic notation of the given move in the context of
the current position.
"""
return self._algebraic(move, long=True) | [
"def",
"lan",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"str",
":",
"return",
"self",
".",
"_algebraic",
"(",
"move",
",",
"long",
"=",
"True",
")"
] | Gets the long algebraic notation of the given move in the context of
the current position. | [
"Gets",
"the",
"long",
"algebraic",
"notation",
"of",
"the",
"given",
"move",
"in",
"the",
"context",
"of",
"the",
"current",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2568-L2573 | train | 219,751 |
niklasf/python-chess | chess/__init__.py | Board.parse_san | def parse_san(self, san: str) -> Move:
"""
Uses the current position as the context to parse a move in standard
algebraic notation and returns the corresponding move object.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the SAN is invalid or ambiguous.
"""
# Castling.
try:
if san in ["O-O", "O-O+", "O-O#"]:
return next(move for move in self.generate_castling_moves() if self.is_kingside_castling(move))
elif san in ["O-O-O", "O-O-O+", "O-O-O#"]:
return next(move for move in self.generate_castling_moves() if self.is_queenside_castling(move))
except StopIteration:
raise ValueError("illegal san: {!r} in {}".format(san, self.fen()))
# Match normal moves.
match = SAN_REGEX.match(san)
if not match:
# Null moves.
if san in ["--", "Z0"]:
return Move.null()
raise ValueError("invalid san: {!r}".format(san))
# Get target square.
to_square = SQUARE_NAMES.index(match.group(4))
to_mask = BB_SQUARES[to_square] & ~self.occupied_co[self.turn]
# Get the promotion type.
p = match.group(5)
promotion = p and PIECE_SYMBOLS.index(p[-1].lower())
# Filter by piece type.
if match.group(1):
piece_type = PIECE_SYMBOLS.index(match.group(1).lower())
from_mask = self.pieces_mask(piece_type, self.turn)
else:
from_mask = self.pawns
# Filter by source file.
if match.group(2):
from_mask &= BB_FILES[FILE_NAMES.index(match.group(2))]
# Filter by source rank.
if match.group(3):
from_mask &= BB_RANKS[int(match.group(3)) - 1]
# Match legal moves.
matched_move = None
for move in self.generate_legal_moves(from_mask, to_mask):
if move.promotion != promotion:
continue
if matched_move:
raise ValueError("ambiguous san: {!r} in {}".format(san, self.fen()))
matched_move = move
if not matched_move:
raise ValueError("illegal san: {!r} in {}".format(san, self.fen()))
return matched_move | python | def parse_san(self, san: str) -> Move:
"""
Uses the current position as the context to parse a move in standard
algebraic notation and returns the corresponding move object.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the SAN is invalid or ambiguous.
"""
# Castling.
try:
if san in ["O-O", "O-O+", "O-O#"]:
return next(move for move in self.generate_castling_moves() if self.is_kingside_castling(move))
elif san in ["O-O-O", "O-O-O+", "O-O-O#"]:
return next(move for move in self.generate_castling_moves() if self.is_queenside_castling(move))
except StopIteration:
raise ValueError("illegal san: {!r} in {}".format(san, self.fen()))
# Match normal moves.
match = SAN_REGEX.match(san)
if not match:
# Null moves.
if san in ["--", "Z0"]:
return Move.null()
raise ValueError("invalid san: {!r}".format(san))
# Get target square.
to_square = SQUARE_NAMES.index(match.group(4))
to_mask = BB_SQUARES[to_square] & ~self.occupied_co[self.turn]
# Get the promotion type.
p = match.group(5)
promotion = p and PIECE_SYMBOLS.index(p[-1].lower())
# Filter by piece type.
if match.group(1):
piece_type = PIECE_SYMBOLS.index(match.group(1).lower())
from_mask = self.pieces_mask(piece_type, self.turn)
else:
from_mask = self.pawns
# Filter by source file.
if match.group(2):
from_mask &= BB_FILES[FILE_NAMES.index(match.group(2))]
# Filter by source rank.
if match.group(3):
from_mask &= BB_RANKS[int(match.group(3)) - 1]
# Match legal moves.
matched_move = None
for move in self.generate_legal_moves(from_mask, to_mask):
if move.promotion != promotion:
continue
if matched_move:
raise ValueError("ambiguous san: {!r} in {}".format(san, self.fen()))
matched_move = move
if not matched_move:
raise ValueError("illegal san: {!r} in {}".format(san, self.fen()))
return matched_move | [
"def",
"parse_san",
"(",
"self",
",",
"san",
":",
"str",
")",
"->",
"Move",
":",
"# Castling.",
"try",
":",
"if",
"san",
"in",
"[",
"\"O-O\"",
",",
"\"O-O+\"",
",",
"\"O-O#\"",
"]",
":",
"return",
"next",
"(",
"move",
"for",
"move",
"in",
"self",
"... | Uses the current position as the context to parse a move in standard
algebraic notation and returns the corresponding move object.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the SAN is invalid or ambiguous. | [
"Uses",
"the",
"current",
"position",
"as",
"the",
"context",
"to",
"parse",
"a",
"move",
"in",
"standard",
"algebraic",
"notation",
"and",
"returns",
"the",
"corresponding",
"move",
"object",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2698-L2762 | train | 219,752 |
niklasf/python-chess | chess/__init__.py | Board.push_san | def push_san(self, san: str) -> Move:
"""
Parses a move in standard algebraic notation, makes the move and puts
it on the the move stack.
Returns the move.
:raises: :exc:`ValueError` if neither legal nor a null move.
"""
move = self.parse_san(san)
self.push(move)
return move | python | def push_san(self, san: str) -> Move:
"""
Parses a move in standard algebraic notation, makes the move and puts
it on the the move stack.
Returns the move.
:raises: :exc:`ValueError` if neither legal nor a null move.
"""
move = self.parse_san(san)
self.push(move)
return move | [
"def",
"push_san",
"(",
"self",
",",
"san",
":",
"str",
")",
"->",
"Move",
":",
"move",
"=",
"self",
".",
"parse_san",
"(",
"san",
")",
"self",
".",
"push",
"(",
"move",
")",
"return",
"move"
] | Parses a move in standard algebraic notation, makes the move and puts
it on the the move stack.
Returns the move.
:raises: :exc:`ValueError` if neither legal nor a null move. | [
"Parses",
"a",
"move",
"in",
"standard",
"algebraic",
"notation",
"makes",
"the",
"move",
"and",
"puts",
"it",
"on",
"the",
"the",
"move",
"stack",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2764-L2775 | train | 219,753 |
niklasf/python-chess | chess/__init__.py | Board.uci | def uci(self, move: Move, *, chess960: Optional[bool] = None) -> str:
"""
Gets the UCI notation of the move.
*chess960* defaults to the mode of the board. Pass ``True`` to force
Chess960 mode.
"""
if chess960 is None:
chess960 = self.chess960
move = self._to_chess960(move)
move = self._from_chess960(chess960, move.from_square, move.to_square, move.promotion, move.drop)
return move.uci() | python | def uci(self, move: Move, *, chess960: Optional[bool] = None) -> str:
"""
Gets the UCI notation of the move.
*chess960* defaults to the mode of the board. Pass ``True`` to force
Chess960 mode.
"""
if chess960 is None:
chess960 = self.chess960
move = self._to_chess960(move)
move = self._from_chess960(chess960, move.from_square, move.to_square, move.promotion, move.drop)
return move.uci() | [
"def",
"uci",
"(",
"self",
",",
"move",
":",
"Move",
",",
"*",
",",
"chess960",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
")",
"->",
"str",
":",
"if",
"chess960",
"is",
"None",
":",
"chess960",
"=",
"self",
".",
"chess960",
"move",
"=",
"se... | Gets the UCI notation of the move.
*chess960* defaults to the mode of the board. Pass ``True`` to force
Chess960 mode. | [
"Gets",
"the",
"UCI",
"notation",
"of",
"the",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2777-L2789 | train | 219,754 |
niklasf/python-chess | chess/__init__.py | Board.parse_uci | def parse_uci(self, uci: str) -> Move:
"""
Parses the given move in UCI notation.
Supports both Chess960 and standard UCI notation.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the move is invalid or illegal in the
current position (but not a null move).
"""
move = Move.from_uci(uci)
if not move:
return move
move = self._to_chess960(move)
move = self._from_chess960(self.chess960, move.from_square, move.to_square, move.promotion, move.drop)
if not self.is_legal(move):
raise ValueError("illegal uci: {!r} in {}".format(uci, self.fen()))
return move | python | def parse_uci(self, uci: str) -> Move:
"""
Parses the given move in UCI notation.
Supports both Chess960 and standard UCI notation.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the move is invalid or illegal in the
current position (but not a null move).
"""
move = Move.from_uci(uci)
if not move:
return move
move = self._to_chess960(move)
move = self._from_chess960(self.chess960, move.from_square, move.to_square, move.promotion, move.drop)
if not self.is_legal(move):
raise ValueError("illegal uci: {!r} in {}".format(uci, self.fen()))
return move | [
"def",
"parse_uci",
"(",
"self",
",",
"uci",
":",
"str",
")",
"->",
"Move",
":",
"move",
"=",
"Move",
".",
"from_uci",
"(",
"uci",
")",
"if",
"not",
"move",
":",
"return",
"move",
"move",
"=",
"self",
".",
"_to_chess960",
"(",
"move",
")",
"move",
... | Parses the given move in UCI notation.
Supports both Chess960 and standard UCI notation.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the move is invalid or illegal in the
current position (but not a null move). | [
"Parses",
"the",
"given",
"move",
"in",
"UCI",
"notation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2791-L2813 | train | 219,755 |
niklasf/python-chess | chess/__init__.py | Board.push_uci | def push_uci(self, uci: str) -> Move:
"""
Parses a move in UCI notation and puts it on the move stack.
Returns the move.
:raises: :exc:`ValueError` if the move is invalid or illegal in the
current position (but not a null move).
"""
move = self.parse_uci(uci)
self.push(move)
return move | python | def push_uci(self, uci: str) -> Move:
"""
Parses a move in UCI notation and puts it on the move stack.
Returns the move.
:raises: :exc:`ValueError` if the move is invalid or illegal in the
current position (but not a null move).
"""
move = self.parse_uci(uci)
self.push(move)
return move | [
"def",
"push_uci",
"(",
"self",
",",
"uci",
":",
"str",
")",
"->",
"Move",
":",
"move",
"=",
"self",
".",
"parse_uci",
"(",
"uci",
")",
"self",
".",
"push",
"(",
"move",
")",
"return",
"move"
] | Parses a move in UCI notation and puts it on the move stack.
Returns the move.
:raises: :exc:`ValueError` if the move is invalid or illegal in the
current position (but not a null move). | [
"Parses",
"a",
"move",
"in",
"UCI",
"notation",
"and",
"puts",
"it",
"on",
"the",
"move",
"stack",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2815-L2826 | train | 219,756 |
niklasf/python-chess | chess/__init__.py | Board.is_en_passant | def is_en_passant(self, move: Move) -> bool:
"""Checks if the given pseudo-legal move is an en passant capture."""
return (self.ep_square == move.to_square and
bool(self.pawns & BB_SQUARES[move.from_square]) and
abs(move.to_square - move.from_square) in [7, 9] and
not self.occupied & BB_SQUARES[move.to_square]) | python | def is_en_passant(self, move: Move) -> bool:
"""Checks if the given pseudo-legal move is an en passant capture."""
return (self.ep_square == move.to_square and
bool(self.pawns & BB_SQUARES[move.from_square]) and
abs(move.to_square - move.from_square) in [7, 9] and
not self.occupied & BB_SQUARES[move.to_square]) | [
"def",
"is_en_passant",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"return",
"(",
"self",
".",
"ep_square",
"==",
"move",
".",
"to_square",
"and",
"bool",
"(",
"self",
".",
"pawns",
"&",
"BB_SQUARES",
"[",
"move",
".",
"from_square"... | Checks if the given pseudo-legal move is an en passant capture. | [
"Checks",
"if",
"the",
"given",
"pseudo",
"-",
"legal",
"move",
"is",
"an",
"en",
"passant",
"capture",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2865-L2870 | train | 219,757 |
niklasf/python-chess | chess/__init__.py | Board.is_capture | def is_capture(self, move: Move) -> bool:
"""Checks if the given pseudo-legal move is a capture."""
return bool(BB_SQUARES[move.to_square] & self.occupied_co[not self.turn]) or self.is_en_passant(move) | python | def is_capture(self, move: Move) -> bool:
"""Checks if the given pseudo-legal move is a capture."""
return bool(BB_SQUARES[move.to_square] & self.occupied_co[not self.turn]) or self.is_en_passant(move) | [
"def",
"is_capture",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"BB_SQUARES",
"[",
"move",
".",
"to_square",
"]",
"&",
"self",
".",
"occupied_co",
"[",
"not",
"self",
".",
"turn",
"]",
")",
"or",
"self",
"... | Checks if the given pseudo-legal move is a capture. | [
"Checks",
"if",
"the",
"given",
"pseudo",
"-",
"legal",
"move",
"is",
"a",
"capture",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2872-L2874 | train | 219,758 |
niklasf/python-chess | chess/__init__.py | Board.is_zeroing | def is_zeroing(self, move: Move) -> bool:
"""Checks if the given pseudo-legal move is a capture or pawn move."""
return bool(BB_SQUARES[move.from_square] & self.pawns or BB_SQUARES[move.to_square] & self.occupied_co[not self.turn]) | python | def is_zeroing(self, move: Move) -> bool:
"""Checks if the given pseudo-legal move is a capture or pawn move."""
return bool(BB_SQUARES[move.from_square] & self.pawns or BB_SQUARES[move.to_square] & self.occupied_co[not self.turn]) | [
"def",
"is_zeroing",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"BB_SQUARES",
"[",
"move",
".",
"from_square",
"]",
"&",
"self",
".",
"pawns",
"or",
"BB_SQUARES",
"[",
"move",
".",
"to_square",
"]",
"&",
"se... | Checks if the given pseudo-legal move is a capture or pawn move. | [
"Checks",
"if",
"the",
"given",
"pseudo",
"-",
"legal",
"move",
"is",
"a",
"capture",
"or",
"pawn",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2876-L2878 | train | 219,759 |
niklasf/python-chess | chess/__init__.py | Board.is_irreversible | def is_irreversible(self, move: Move) -> bool:
"""
Checks if the given pseudo-legal move is irreversible.
In standard chess, pawn moves, captures and moves that destroy castling
rights are irreversible.
"""
backrank = BB_RANK_1 if self.turn == WHITE else BB_RANK_8
cr = self.clean_castling_rights() & backrank
return bool(self.is_zeroing(move) or
cr and BB_SQUARES[move.from_square] & self.kings & ~self.promoted or
cr & BB_SQUARES[move.from_square] or
cr & BB_SQUARES[move.to_square]) | python | def is_irreversible(self, move: Move) -> bool:
"""
Checks if the given pseudo-legal move is irreversible.
In standard chess, pawn moves, captures and moves that destroy castling
rights are irreversible.
"""
backrank = BB_RANK_1 if self.turn == WHITE else BB_RANK_8
cr = self.clean_castling_rights() & backrank
return bool(self.is_zeroing(move) or
cr and BB_SQUARES[move.from_square] & self.kings & ~self.promoted or
cr & BB_SQUARES[move.from_square] or
cr & BB_SQUARES[move.to_square]) | [
"def",
"is_irreversible",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"backrank",
"=",
"BB_RANK_1",
"if",
"self",
".",
"turn",
"==",
"WHITE",
"else",
"BB_RANK_8",
"cr",
"=",
"self",
".",
"clean_castling_rights",
"(",
")",
"&",
"backran... | Checks if the given pseudo-legal move is irreversible.
In standard chess, pawn moves, captures and moves that destroy castling
rights are irreversible. | [
"Checks",
"if",
"the",
"given",
"pseudo",
"-",
"legal",
"move",
"is",
"irreversible",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2880-L2892 | train | 219,760 |
niklasf/python-chess | chess/__init__.py | Board.is_castling | def is_castling(self, move: Move) -> bool:
"""Checks if the given pseudo-legal move is a castling move."""
if self.kings & BB_SQUARES[move.from_square]:
diff = square_file(move.from_square) - square_file(move.to_square)
return abs(diff) > 1 or bool(self.rooks & self.occupied_co[self.turn] & BB_SQUARES[move.to_square])
return False | python | def is_castling(self, move: Move) -> bool:
"""Checks if the given pseudo-legal move is a castling move."""
if self.kings & BB_SQUARES[move.from_square]:
diff = square_file(move.from_square) - square_file(move.to_square)
return abs(diff) > 1 or bool(self.rooks & self.occupied_co[self.turn] & BB_SQUARES[move.to_square])
return False | [
"def",
"is_castling",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"if",
"self",
".",
"kings",
"&",
"BB_SQUARES",
"[",
"move",
".",
"from_square",
"]",
":",
"diff",
"=",
"square_file",
"(",
"move",
".",
"from_square",
")",
"-",
"squ... | Checks if the given pseudo-legal move is a castling move. | [
"Checks",
"if",
"the",
"given",
"pseudo",
"-",
"legal",
"move",
"is",
"a",
"castling",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2894-L2899 | train | 219,761 |
niklasf/python-chess | chess/__init__.py | Board.is_kingside_castling | def is_kingside_castling(self, move: Move) -> bool:
"""
Checks if the given pseudo-legal move is a kingside castling move.
"""
return self.is_castling(move) and square_file(move.to_square) > square_file(move.from_square) | python | def is_kingside_castling(self, move: Move) -> bool:
"""
Checks if the given pseudo-legal move is a kingside castling move.
"""
return self.is_castling(move) and square_file(move.to_square) > square_file(move.from_square) | [
"def",
"is_kingside_castling",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"return",
"self",
".",
"is_castling",
"(",
"move",
")",
"and",
"square_file",
"(",
"move",
".",
"to_square",
")",
">",
"square_file",
"(",
"move",
".",
"from_sq... | Checks if the given pseudo-legal move is a kingside castling move. | [
"Checks",
"if",
"the",
"given",
"pseudo",
"-",
"legal",
"move",
"is",
"a",
"kingside",
"castling",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2901-L2905 | train | 219,762 |
niklasf/python-chess | chess/__init__.py | Board.has_castling_rights | def has_castling_rights(self, color: Color) -> bool:
"""Checks if the given side has castling rights."""
backrank = BB_RANK_1 if color == WHITE else BB_RANK_8
return bool(self.clean_castling_rights() & backrank) | python | def has_castling_rights(self, color: Color) -> bool:
"""Checks if the given side has castling rights."""
backrank = BB_RANK_1 if color == WHITE else BB_RANK_8
return bool(self.clean_castling_rights() & backrank) | [
"def",
"has_castling_rights",
"(",
"self",
",",
"color",
":",
"Color",
")",
"->",
"bool",
":",
"backrank",
"=",
"BB_RANK_1",
"if",
"color",
"==",
"WHITE",
"else",
"BB_RANK_8",
"return",
"bool",
"(",
"self",
".",
"clean_castling_rights",
"(",
")",
"&",
"bac... | Checks if the given side has castling rights. | [
"Checks",
"if",
"the",
"given",
"side",
"has",
"castling",
"rights",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2969-L2972 | train | 219,763 |
niklasf/python-chess | chess/__init__.py | Board.has_chess960_castling_rights | def has_chess960_castling_rights(self) -> bool:
"""
Checks if there are castling rights that are only possible in Chess960.
"""
# Get valid Chess960 castling rights.
chess960 = self.chess960
self.chess960 = True
castling_rights = self.clean_castling_rights()
self.chess960 = chess960
# Standard chess castling rights can only be on the standard
# starting rook squares.
if castling_rights & ~BB_CORNERS:
return True
# If there are any castling rights in standard chess, the king must be
# on e1 or e8.
if castling_rights & BB_RANK_1 and not self.occupied_co[WHITE] & self.kings & BB_E1:
return True
if castling_rights & BB_RANK_8 and not self.occupied_co[BLACK] & self.kings & BB_E8:
return True
return False | python | def has_chess960_castling_rights(self) -> bool:
"""
Checks if there are castling rights that are only possible in Chess960.
"""
# Get valid Chess960 castling rights.
chess960 = self.chess960
self.chess960 = True
castling_rights = self.clean_castling_rights()
self.chess960 = chess960
# Standard chess castling rights can only be on the standard
# starting rook squares.
if castling_rights & ~BB_CORNERS:
return True
# If there are any castling rights in standard chess, the king must be
# on e1 or e8.
if castling_rights & BB_RANK_1 and not self.occupied_co[WHITE] & self.kings & BB_E1:
return True
if castling_rights & BB_RANK_8 and not self.occupied_co[BLACK] & self.kings & BB_E8:
return True
return False | [
"def",
"has_chess960_castling_rights",
"(",
"self",
")",
"->",
"bool",
":",
"# Get valid Chess960 castling rights.",
"chess960",
"=",
"self",
".",
"chess960",
"self",
".",
"chess960",
"=",
"True",
"castling_rights",
"=",
"self",
".",
"clean_castling_rights",
"(",
")... | Checks if there are castling rights that are only possible in Chess960. | [
"Checks",
"if",
"there",
"are",
"castling",
"rights",
"that",
"are",
"only",
"possible",
"in",
"Chess960",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L3016-L3038 | train | 219,764 |
niklasf/python-chess | chess/__init__.py | Board.status | def status(self) -> Status:
"""
Gets a bitmask of possible problems with the position.
Move making, generation and validation are only guaranteed to work on
a completely valid board.
:data:`~chess.STATUS_VALID` for a completely valid board.
Otherwise, bitwise combinations of:
:data:`~chess.STATUS_NO_WHITE_KING`,
:data:`~chess.STATUS_NO_BLACK_KING`,
:data:`~chess.STATUS_TOO_MANY_KINGS`,
:data:`~chess.STATUS_TOO_MANY_WHITE_PAWNS`,
:data:`~chess.STATUS_TOO_MANY_BLACK_PAWNS`,
:data:`~chess.STATUS_PAWNS_ON_BACKRANK`,
:data:`~chess.STATUS_TOO_MANY_WHITE_PIECES`,
:data:`~chess.STATUS_TOO_MANY_BLACK_PIECES`,
:data:`~chess.STATUS_BAD_CASTLING_RIGHTS`,
:data:`~chess.STATUS_INVALID_EP_SQUARE`,
:data:`~chess.STATUS_OPPOSITE_CHECK`,
:data:`~chess.STATUS_EMPTY`,
:data:`~chess.STATUS_RACE_CHECK`,
:data:`~chess.STATUS_RACE_OVER`,
:data:`~chess.STATUS_RACE_MATERIAL`.
"""
errors = STATUS_VALID
# There must be at least one piece.
if not self.occupied:
errors |= STATUS_EMPTY
# There must be exactly one king of each color.
if not self.occupied_co[WHITE] & self.kings:
errors |= STATUS_NO_WHITE_KING
if not self.occupied_co[BLACK] & self.kings:
errors |= STATUS_NO_BLACK_KING
if popcount(self.occupied & self.kings) > 2:
errors |= STATUS_TOO_MANY_KINGS
# There can not be more than 16 pieces of any color.
if popcount(self.occupied_co[WHITE]) > 16:
errors |= STATUS_TOO_MANY_WHITE_PIECES
if popcount(self.occupied_co[BLACK]) > 16:
errors |= STATUS_TOO_MANY_BLACK_PIECES
# There can not be more than 8 pawns of any color.
if popcount(self.occupied_co[WHITE] & self.pawns) > 8:
errors |= STATUS_TOO_MANY_WHITE_PAWNS
if popcount(self.occupied_co[BLACK] & self.pawns) > 8:
errors |= STATUS_TOO_MANY_BLACK_PAWNS
# Pawns can not be on the back rank.
if self.pawns & BB_BACKRANKS:
errors |= STATUS_PAWNS_ON_BACKRANK
# Castling rights.
if self.castling_rights != self.clean_castling_rights():
errors |= STATUS_BAD_CASTLING_RIGHTS
# En passant.
if self.ep_square != self._valid_ep_square():
errors |= STATUS_INVALID_EP_SQUARE
# Side to move giving check.
if self.was_into_check():
errors |= STATUS_OPPOSITE_CHECK
return errors | python | def status(self) -> Status:
"""
Gets a bitmask of possible problems with the position.
Move making, generation and validation are only guaranteed to work on
a completely valid board.
:data:`~chess.STATUS_VALID` for a completely valid board.
Otherwise, bitwise combinations of:
:data:`~chess.STATUS_NO_WHITE_KING`,
:data:`~chess.STATUS_NO_BLACK_KING`,
:data:`~chess.STATUS_TOO_MANY_KINGS`,
:data:`~chess.STATUS_TOO_MANY_WHITE_PAWNS`,
:data:`~chess.STATUS_TOO_MANY_BLACK_PAWNS`,
:data:`~chess.STATUS_PAWNS_ON_BACKRANK`,
:data:`~chess.STATUS_TOO_MANY_WHITE_PIECES`,
:data:`~chess.STATUS_TOO_MANY_BLACK_PIECES`,
:data:`~chess.STATUS_BAD_CASTLING_RIGHTS`,
:data:`~chess.STATUS_INVALID_EP_SQUARE`,
:data:`~chess.STATUS_OPPOSITE_CHECK`,
:data:`~chess.STATUS_EMPTY`,
:data:`~chess.STATUS_RACE_CHECK`,
:data:`~chess.STATUS_RACE_OVER`,
:data:`~chess.STATUS_RACE_MATERIAL`.
"""
errors = STATUS_VALID
# There must be at least one piece.
if not self.occupied:
errors |= STATUS_EMPTY
# There must be exactly one king of each color.
if not self.occupied_co[WHITE] & self.kings:
errors |= STATUS_NO_WHITE_KING
if not self.occupied_co[BLACK] & self.kings:
errors |= STATUS_NO_BLACK_KING
if popcount(self.occupied & self.kings) > 2:
errors |= STATUS_TOO_MANY_KINGS
# There can not be more than 16 pieces of any color.
if popcount(self.occupied_co[WHITE]) > 16:
errors |= STATUS_TOO_MANY_WHITE_PIECES
if popcount(self.occupied_co[BLACK]) > 16:
errors |= STATUS_TOO_MANY_BLACK_PIECES
# There can not be more than 8 pawns of any color.
if popcount(self.occupied_co[WHITE] & self.pawns) > 8:
errors |= STATUS_TOO_MANY_WHITE_PAWNS
if popcount(self.occupied_co[BLACK] & self.pawns) > 8:
errors |= STATUS_TOO_MANY_BLACK_PAWNS
# Pawns can not be on the back rank.
if self.pawns & BB_BACKRANKS:
errors |= STATUS_PAWNS_ON_BACKRANK
# Castling rights.
if self.castling_rights != self.clean_castling_rights():
errors |= STATUS_BAD_CASTLING_RIGHTS
# En passant.
if self.ep_square != self._valid_ep_square():
errors |= STATUS_INVALID_EP_SQUARE
# Side to move giving check.
if self.was_into_check():
errors |= STATUS_OPPOSITE_CHECK
return errors | [
"def",
"status",
"(",
"self",
")",
"->",
"Status",
":",
"errors",
"=",
"STATUS_VALID",
"# There must be at least one piece.",
"if",
"not",
"self",
".",
"occupied",
":",
"errors",
"|=",
"STATUS_EMPTY",
"# There must be exactly one king of each color.",
"if",
"not",
"se... | Gets a bitmask of possible problems with the position.
Move making, generation and validation are only guaranteed to work on
a completely valid board.
:data:`~chess.STATUS_VALID` for a completely valid board.
Otherwise, bitwise combinations of:
:data:`~chess.STATUS_NO_WHITE_KING`,
:data:`~chess.STATUS_NO_BLACK_KING`,
:data:`~chess.STATUS_TOO_MANY_KINGS`,
:data:`~chess.STATUS_TOO_MANY_WHITE_PAWNS`,
:data:`~chess.STATUS_TOO_MANY_BLACK_PAWNS`,
:data:`~chess.STATUS_PAWNS_ON_BACKRANK`,
:data:`~chess.STATUS_TOO_MANY_WHITE_PIECES`,
:data:`~chess.STATUS_TOO_MANY_BLACK_PIECES`,
:data:`~chess.STATUS_BAD_CASTLING_RIGHTS`,
:data:`~chess.STATUS_INVALID_EP_SQUARE`,
:data:`~chess.STATUS_OPPOSITE_CHECK`,
:data:`~chess.STATUS_EMPTY`,
:data:`~chess.STATUS_RACE_CHECK`,
:data:`~chess.STATUS_RACE_OVER`,
:data:`~chess.STATUS_RACE_MATERIAL`. | [
"Gets",
"a",
"bitmask",
"of",
"possible",
"problems",
"with",
"the",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L3040-L3108 | train | 219,765 |
niklasf/python-chess | chess/__init__.py | SquareSet.remove | def remove(self, square: Square) -> None:
"""
Removes a square from the set.
:raises: :exc:`KeyError` if the given square was not in the set.
"""
mask = BB_SQUARES[square]
if self.mask & mask:
self.mask ^= mask
else:
raise KeyError(square) | python | def remove(self, square: Square) -> None:
"""
Removes a square from the set.
:raises: :exc:`KeyError` if the given square was not in the set.
"""
mask = BB_SQUARES[square]
if self.mask & mask:
self.mask ^= mask
else:
raise KeyError(square) | [
"def",
"remove",
"(",
"self",
",",
"square",
":",
"Square",
")",
"->",
"None",
":",
"mask",
"=",
"BB_SQUARES",
"[",
"square",
"]",
"if",
"self",
".",
"mask",
"&",
"mask",
":",
"self",
".",
"mask",
"^=",
"mask",
"else",
":",
"raise",
"KeyError",
"("... | Removes a square from the set.
:raises: :exc:`KeyError` if the given square was not in the set. | [
"Removes",
"a",
"square",
"from",
"the",
"set",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L3695-L3705 | train | 219,766 |
niklasf/python-chess | chess/__init__.py | SquareSet.pop | def pop(self) -> Square:
"""
Removes a square from the set and returns it.
:raises: :exc:`KeyError` on an empty set.
"""
if not self.mask:
raise KeyError("pop from empty SquareSet")
square = lsb(self.mask)
self.mask &= (self.mask - 1)
return square | python | def pop(self) -> Square:
"""
Removes a square from the set and returns it.
:raises: :exc:`KeyError` on an empty set.
"""
if not self.mask:
raise KeyError("pop from empty SquareSet")
square = lsb(self.mask)
self.mask &= (self.mask - 1)
return square | [
"def",
"pop",
"(",
"self",
")",
"->",
"Square",
":",
"if",
"not",
"self",
".",
"mask",
":",
"raise",
"KeyError",
"(",
"\"pop from empty SquareSet\"",
")",
"square",
"=",
"lsb",
"(",
"self",
".",
"mask",
")",
"self",
".",
"mask",
"&=",
"(",
"self",
".... | Removes a square from the set and returns it.
:raises: :exc:`KeyError` on an empty set. | [
"Removes",
"a",
"square",
"from",
"the",
"set",
"and",
"returns",
"it",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L3707-L3718 | train | 219,767 |
niklasf/python-chess | chess/__init__.py | SquareSet.tolist | def tolist(self) -> List[bool]:
"""Convert the set to a list of 64 bools."""
result = [False] * 64
for square in self:
result[square] = True
return result | python | def tolist(self) -> List[bool]:
"""Convert the set to a list of 64 bools."""
result = [False] * 64
for square in self:
result[square] = True
return result | [
"def",
"tolist",
"(",
"self",
")",
"->",
"List",
"[",
"bool",
"]",
":",
"result",
"=",
"[",
"False",
"]",
"*",
"64",
"for",
"square",
"in",
"self",
":",
"result",
"[",
"square",
"]",
"=",
"True",
"return",
"result"
] | Convert the set to a list of 64 bools. | [
"Convert",
"the",
"set",
"to",
"a",
"list",
"of",
"64",
"bools",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L3734-L3739 | train | 219,768 |
niklasf/python-chess | chess/variant.py | find_variant | def find_variant(name: str) -> Type[chess.Board]:
"""Looks for a variant board class by variant name."""
for variant in VARIANTS:
if any(alias.lower() == name.lower() for alias in variant.aliases):
return variant
raise ValueError("unsupported variant: {}".format(name)) | python | def find_variant(name: str) -> Type[chess.Board]:
"""Looks for a variant board class by variant name."""
for variant in VARIANTS:
if any(alias.lower() == name.lower() for alias in variant.aliases):
return variant
raise ValueError("unsupported variant: {}".format(name)) | [
"def",
"find_variant",
"(",
"name",
":",
"str",
")",
"->",
"Type",
"[",
"chess",
".",
"Board",
"]",
":",
"for",
"variant",
"in",
"VARIANTS",
":",
"if",
"any",
"(",
"alias",
".",
"lower",
"(",
")",
"==",
"name",
".",
"lower",
"(",
")",
"for",
"ali... | Looks for a variant board class by variant name. | [
"Looks",
"for",
"a",
"variant",
"board",
"class",
"by",
"variant",
"name",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/variant.py#L862-L867 | train | 219,769 |
niklasf/python-chess | chess/polyglot.py | zobrist_hash | def zobrist_hash(board: chess.Board, *, _hasher: Callable[[chess.Board], int] = ZobristHasher(POLYGLOT_RANDOM_ARRAY)) -> int:
"""
Calculates the Polyglot Zobrist hash of the position.
A Zobrist hash is an XOR of pseudo-random values picked from
an array. Which values are picked is decided by features of the
position, such as piece positions, castling rights and en passant
squares.
"""
return _hasher(board) | python | def zobrist_hash(board: chess.Board, *, _hasher: Callable[[chess.Board], int] = ZobristHasher(POLYGLOT_RANDOM_ARRAY)) -> int:
"""
Calculates the Polyglot Zobrist hash of the position.
A Zobrist hash is an XOR of pseudo-random values picked from
an array. Which values are picked is decided by features of the
position, such as piece positions, castling rights and en passant
squares.
"""
return _hasher(board) | [
"def",
"zobrist_hash",
"(",
"board",
":",
"chess",
".",
"Board",
",",
"*",
",",
"_hasher",
":",
"Callable",
"[",
"[",
"chess",
".",
"Board",
"]",
",",
"int",
"]",
"=",
"ZobristHasher",
"(",
"POLYGLOT_RANDOM_ARRAY",
")",
")",
"->",
"int",
":",
"return",... | Calculates the Polyglot Zobrist hash of the position.
A Zobrist hash is an XOR of pseudo-random values picked from
an array. Which values are picked is decided by features of the
position, such as piece positions, castling rights and en passant
squares. | [
"Calculates",
"the",
"Polyglot",
"Zobrist",
"hash",
"of",
"the",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/polyglot.py#L291-L300 | train | 219,770 |
niklasf/python-chess | chess/polyglot.py | MemoryMappedReader.find_all | def find_all(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = ()) -> Iterator[Entry]:
"""Seeks a specific position and yields corresponding entries."""
try:
key = int(board) # type: ignore
context = None # type: Optional[chess.Board]
except (TypeError, ValueError):
context = typing.cast(chess.Board, board)
key = zobrist_hash(context)
i = self.bisect_key_left(key)
size = len(self)
while i < size:
entry = self[i]
i += 1
if entry.key != key:
break
if entry.weight < minimum_weight:
continue
if context:
move = context._from_chess960(context.chess960, entry.move.from_square, entry.move.to_square, entry.move.promotion, entry.move.drop)
entry = Entry(entry.key, entry.raw_move, entry.weight, entry.learn, move)
if exclude_moves and entry.move in exclude_moves:
continue
if context and not context.is_legal(entry.move):
continue
yield entry | python | def find_all(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = ()) -> Iterator[Entry]:
"""Seeks a specific position and yields corresponding entries."""
try:
key = int(board) # type: ignore
context = None # type: Optional[chess.Board]
except (TypeError, ValueError):
context = typing.cast(chess.Board, board)
key = zobrist_hash(context)
i = self.bisect_key_left(key)
size = len(self)
while i < size:
entry = self[i]
i += 1
if entry.key != key:
break
if entry.weight < minimum_weight:
continue
if context:
move = context._from_chess960(context.chess960, entry.move.from_square, entry.move.to_square, entry.move.promotion, entry.move.drop)
entry = Entry(entry.key, entry.raw_move, entry.weight, entry.learn, move)
if exclude_moves and entry.move in exclude_moves:
continue
if context and not context.is_legal(entry.move):
continue
yield entry | [
"def",
"find_all",
"(",
"self",
",",
"board",
":",
"Union",
"[",
"chess",
".",
"Board",
",",
"int",
"]",
",",
"*",
",",
"minimum_weight",
":",
"int",
"=",
"1",
",",
"exclude_moves",
":",
"Container",
"[",
"chess",
".",
"Move",
"]",
"=",
"(",
")",
... | Seeks a specific position and yields corresponding entries. | [
"Seeks",
"a",
"specific",
"position",
"and",
"yields",
"corresponding",
"entries",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/polyglot.py#L387-L419 | train | 219,771 |
niklasf/python-chess | chess/polyglot.py | MemoryMappedReader.find | def find(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = ()) -> Entry:
"""
Finds the main entry for the given position or Zobrist hash.
The main entry is the (first) entry with the highest weight.
By default, entries with weight ``0`` are excluded. This is a common
way to delete entries from an opening book without compacting it. Pass
*minimum_weight* ``0`` to select all entries.
:raises: :exc:`IndexError` if no entries are found. Use
:func:`~chess.polyglot.MemoryMappedReader.get()` if you prefer to
get ``None`` instead of an exception.
"""
try:
return max(self.find_all(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves), key=lambda entry: entry.weight)
except ValueError:
raise IndexError() | python | def find(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = ()) -> Entry:
"""
Finds the main entry for the given position or Zobrist hash.
The main entry is the (first) entry with the highest weight.
By default, entries with weight ``0`` are excluded. This is a common
way to delete entries from an opening book without compacting it. Pass
*minimum_weight* ``0`` to select all entries.
:raises: :exc:`IndexError` if no entries are found. Use
:func:`~chess.polyglot.MemoryMappedReader.get()` if you prefer to
get ``None`` instead of an exception.
"""
try:
return max(self.find_all(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves), key=lambda entry: entry.weight)
except ValueError:
raise IndexError() | [
"def",
"find",
"(",
"self",
",",
"board",
":",
"Union",
"[",
"chess",
".",
"Board",
",",
"int",
"]",
",",
"*",
",",
"minimum_weight",
":",
"int",
"=",
"1",
",",
"exclude_moves",
":",
"Container",
"[",
"chess",
".",
"Move",
"]",
"=",
"(",
")",
")"... | Finds the main entry for the given position or Zobrist hash.
The main entry is the (first) entry with the highest weight.
By default, entries with weight ``0`` are excluded. This is a common
way to delete entries from an opening book without compacting it. Pass
*minimum_weight* ``0`` to select all entries.
:raises: :exc:`IndexError` if no entries are found. Use
:func:`~chess.polyglot.MemoryMappedReader.get()` if you prefer to
get ``None`` instead of an exception. | [
"Finds",
"the",
"main",
"entry",
"for",
"the",
"given",
"position",
"or",
"Zobrist",
"hash",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/polyglot.py#L421-L438 | train | 219,772 |
niklasf/python-chess | chess/polyglot.py | MemoryMappedReader.choice | def choice(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = (), random=random) -> Entry:
"""
Uniformly selects a random entry for the given position.
:raises: :exc:`IndexError` if no entries are found.
"""
chosen_entry = None
for i, entry in enumerate(self.find_all(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves)):
if chosen_entry is None or random.randint(0, i) == i:
chosen_entry = entry
if chosen_entry is None:
raise IndexError()
return chosen_entry | python | def choice(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = (), random=random) -> Entry:
"""
Uniformly selects a random entry for the given position.
:raises: :exc:`IndexError` if no entries are found.
"""
chosen_entry = None
for i, entry in enumerate(self.find_all(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves)):
if chosen_entry is None or random.randint(0, i) == i:
chosen_entry = entry
if chosen_entry is None:
raise IndexError()
return chosen_entry | [
"def",
"choice",
"(",
"self",
",",
"board",
":",
"Union",
"[",
"chess",
".",
"Board",
",",
"int",
"]",
",",
"*",
",",
"minimum_weight",
":",
"int",
"=",
"1",
",",
"exclude_moves",
":",
"Container",
"[",
"chess",
".",
"Move",
"]",
"=",
"(",
")",
"... | Uniformly selects a random entry for the given position.
:raises: :exc:`IndexError` if no entries are found. | [
"Uniformly",
"selects",
"a",
"random",
"entry",
"for",
"the",
"given",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/polyglot.py#L446-L461 | train | 219,773 |
niklasf/python-chess | chess/polyglot.py | MemoryMappedReader.weighted_choice | def weighted_choice(self, board: Union[chess.Board, int], *, exclude_moves: Container[chess.Move] = (), random=random) -> Entry:
"""
Selects a random entry for the given position, distributed by the
weights of the entries.
:raises: :exc:`IndexError` if no entries are found.
"""
total_weights = sum(entry.weight for entry in self.find_all(board, exclude_moves=exclude_moves))
if not total_weights:
raise IndexError()
choice = random.randint(0, total_weights - 1)
current_sum = 0
for entry in self.find_all(board, exclude_moves=exclude_moves):
current_sum += entry.weight
if current_sum > choice:
return entry
assert False | python | def weighted_choice(self, board: Union[chess.Board, int], *, exclude_moves: Container[chess.Move] = (), random=random) -> Entry:
"""
Selects a random entry for the given position, distributed by the
weights of the entries.
:raises: :exc:`IndexError` if no entries are found.
"""
total_weights = sum(entry.weight for entry in self.find_all(board, exclude_moves=exclude_moves))
if not total_weights:
raise IndexError()
choice = random.randint(0, total_weights - 1)
current_sum = 0
for entry in self.find_all(board, exclude_moves=exclude_moves):
current_sum += entry.weight
if current_sum > choice:
return entry
assert False | [
"def",
"weighted_choice",
"(",
"self",
",",
"board",
":",
"Union",
"[",
"chess",
".",
"Board",
",",
"int",
"]",
",",
"*",
",",
"exclude_moves",
":",
"Container",
"[",
"chess",
".",
"Move",
"]",
"=",
"(",
")",
",",
"random",
"=",
"random",
")",
"->"... | Selects a random entry for the given position, distributed by the
weights of the entries.
:raises: :exc:`IndexError` if no entries are found. | [
"Selects",
"a",
"random",
"entry",
"for",
"the",
"given",
"position",
"distributed",
"by",
"the",
"weights",
"of",
"the",
"entries",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/polyglot.py#L463-L482 | train | 219,774 |
niklasf/python-chess | chess/polyglot.py | MemoryMappedReader.close | def close(self) -> None:
"""Closes the reader."""
if self.mmap is not None:
self.mmap.close()
try:
os.close(self.fd)
except OSError:
pass | python | def close(self) -> None:
"""Closes the reader."""
if self.mmap is not None:
self.mmap.close()
try:
os.close(self.fd)
except OSError:
pass | [
"def",
"close",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"mmap",
"is",
"not",
"None",
":",
"self",
".",
"mmap",
".",
"close",
"(",
")",
"try",
":",
"os",
".",
"close",
"(",
"self",
".",
"fd",
")",
"except",
"OSError",
":",
"pass"... | Closes the reader. | [
"Closes",
"the",
"reader",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/polyglot.py#L484-L492 | train | 219,775 |
mapbox/mapbox-sdk-py | mapbox/encoding.py | _geom_points | def _geom_points(geom):
"""GeoJSON geometry to a sequence of point tuples
"""
if geom['type'] == 'Point':
yield tuple(geom['coordinates'])
elif geom['type'] in ('MultiPoint', 'LineString'):
for position in geom['coordinates']:
yield tuple(position)
else:
raise InvalidFeatureError(
"Unsupported geometry type:{0}".format(geom['type'])) | python | def _geom_points(geom):
"""GeoJSON geometry to a sequence of point tuples
"""
if geom['type'] == 'Point':
yield tuple(geom['coordinates'])
elif geom['type'] in ('MultiPoint', 'LineString'):
for position in geom['coordinates']:
yield tuple(position)
else:
raise InvalidFeatureError(
"Unsupported geometry type:{0}".format(geom['type'])) | [
"def",
"_geom_points",
"(",
"geom",
")",
":",
"if",
"geom",
"[",
"'type'",
"]",
"==",
"'Point'",
":",
"yield",
"tuple",
"(",
"geom",
"[",
"'coordinates'",
"]",
")",
"elif",
"geom",
"[",
"'type'",
"]",
"in",
"(",
"'MultiPoint'",
",",
"'LineString'",
")"... | GeoJSON geometry to a sequence of point tuples | [
"GeoJSON",
"geometry",
"to",
"a",
"sequence",
"of",
"point",
"tuples"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/encoding.py#L7-L17 | train | 219,776 |
mapbox/mapbox-sdk-py | mapbox/encoding.py | read_points | def read_points(features):
""" Iterable of features to a sequence of point tuples
Where "features" can be either GeoJSON mappings
or objects implementing the geo_interface
"""
for feature in features:
if isinstance(feature, (tuple, list)) and len(feature) == 2:
yield feature
elif hasattr(feature, '__geo_interface__'):
# An object implementing the geo_interface
try:
# Could be a Feature...
geom = feature.__geo_interface__['geometry']
for pt in _geom_points(geom):
yield pt
except KeyError:
# ... or a geometry directly
for pt in _geom_points(feature.__geo_interface__):
yield pt
elif 'type' in feature and feature['type'] == 'Feature':
# A GeoJSON-like mapping
geom = feature['geometry']
for pt in _geom_points(geom):
yield pt
elif 'coordinates' in feature:
geom = feature
for pt in _geom_points(geom):
yield pt
else:
raise InvalidFeatureError(
"Unknown object: Not a GeoJSON Point feature or "
"an object with __geo_interface__:\n{0}".format(feature)) | python | def read_points(features):
""" Iterable of features to a sequence of point tuples
Where "features" can be either GeoJSON mappings
or objects implementing the geo_interface
"""
for feature in features:
if isinstance(feature, (tuple, list)) and len(feature) == 2:
yield feature
elif hasattr(feature, '__geo_interface__'):
# An object implementing the geo_interface
try:
# Could be a Feature...
geom = feature.__geo_interface__['geometry']
for pt in _geom_points(geom):
yield pt
except KeyError:
# ... or a geometry directly
for pt in _geom_points(feature.__geo_interface__):
yield pt
elif 'type' in feature and feature['type'] == 'Feature':
# A GeoJSON-like mapping
geom = feature['geometry']
for pt in _geom_points(geom):
yield pt
elif 'coordinates' in feature:
geom = feature
for pt in _geom_points(geom):
yield pt
else:
raise InvalidFeatureError(
"Unknown object: Not a GeoJSON Point feature or "
"an object with __geo_interface__:\n{0}".format(feature)) | [
"def",
"read_points",
"(",
"features",
")",
":",
"for",
"feature",
"in",
"features",
":",
"if",
"isinstance",
"(",
"feature",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"len",
"(",
"feature",
")",
"==",
"2",
":",
"yield",
"feature",
"elif",
"ha... | Iterable of features to a sequence of point tuples
Where "features" can be either GeoJSON mappings
or objects implementing the geo_interface | [
"Iterable",
"of",
"features",
"to",
"a",
"sequence",
"of",
"point",
"tuples",
"Where",
"features",
"can",
"be",
"either",
"GeoJSON",
"mappings",
"or",
"objects",
"implementing",
"the",
"geo_interface"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/encoding.py#L20-L56 | train | 219,777 |
mapbox/mapbox-sdk-py | mapbox/encoding.py | encode_polyline | def encode_polyline(features):
"""Encode and iterable of features as a polyline
"""
points = list(read_points(features))
latlon_points = [(x[1], x[0]) for x in points]
return polyline.encode(latlon_points) | python | def encode_polyline(features):
"""Encode and iterable of features as a polyline
"""
points = list(read_points(features))
latlon_points = [(x[1], x[0]) for x in points]
return polyline.encode(latlon_points) | [
"def",
"encode_polyline",
"(",
"features",
")",
":",
"points",
"=",
"list",
"(",
"read_points",
"(",
"features",
")",
")",
"latlon_points",
"=",
"[",
"(",
"x",
"[",
"1",
"]",
",",
"x",
"[",
"0",
"]",
")",
"for",
"x",
"in",
"points",
"]",
"return",
... | Encode and iterable of features as a polyline | [
"Encode",
"and",
"iterable",
"of",
"features",
"as",
"a",
"polyline"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/encoding.py#L81-L86 | train | 219,778 |
mapbox/mapbox-sdk-py | mapbox/services/directions.py | Directions.directions | def directions(self, features, profile='mapbox/driving',
alternatives=None, geometries=None, overview=None, steps=None,
continue_straight=None, waypoint_snapping=None, annotations=None,
language=None, **kwargs):
"""Request directions for waypoints encoded as GeoJSON features.
Parameters
----------
features : iterable
An collection of GeoJSON features
profile : str
Name of a Mapbox profile such as 'mapbox.driving'
alternatives : bool
Whether to try to return alternative routes, default: False
geometries : string
Type of geometry returned (geojson, polyline, polyline6)
overview : string or False
Type of returned overview geometry: 'full', 'simplified',
or False
steps : bool
Whether to return steps and turn-by-turn instructions,
default: False
continue_straight : bool
Direction of travel when departing intermediate waypoints
radiuses : iterable of numbers or 'unlimited'
Must be same length as features
waypoint_snapping : list
Controls snapping of waypoints
The list is zipped with the features collection and must
have the same length. Elements of the list must be one of:
- A number (interpretted as a snapping radius)
- The string 'unlimited' (unlimited snapping radius)
- A 3-element tuple consisting of (radius, angle, range)
- None (no snapping parameters specified for that waypoint)
annotations : str
Whether or not to return additional metadata along the route
Possible values are: 'duration', 'distance', 'speed', and
'congestion'. Several annotations can be used by joining
them with ','.
language : str
Language of returned turn-by-turn text instructions,
default: 'en'
Returns
-------
requests.Response
The response object has a geojson() method for access to
the route(s) as a GeoJSON-like FeatureCollection
dictionary.
"""
# backwards compatible, deprecated
if 'geometry' in kwargs and geometries is None:
geometries = kwargs['geometry']
warnings.warn('Use `geometries` instead of `geometry`',
errors.MapboxDeprecationWarning)
annotations = self._validate_annotations(annotations)
coordinates = encode_coordinates(
features, precision=6, min_limit=2, max_limit=25)
geometries = self._validate_geom_encoding(geometries)
overview = self._validate_geom_overview(overview)
profile = self._validate_profile(profile)
bearings, radii = self._validate_snapping(waypoint_snapping, features)
params = {}
if alternatives is not None:
params.update(
{'alternatives': 'true' if alternatives is True else 'false'})
if geometries is not None:
params.update({'geometries': geometries})
if overview is not None:
params.update(
{'overview': 'false' if overview is False else overview})
if steps is not None:
params.update(
{'steps': 'true' if steps is True else 'false'})
if continue_straight is not None:
params.update(
{'continue_straight': 'true' if steps is True else 'false'})
if annotations is not None:
params.update({'annotations': ','.join(annotations)})
if language is not None:
params.update({'language': language})
if radii is not None:
params.update(
{'radiuses': ';'.join(str(r) for r in radii)})
if bearings is not None:
params.update(
{'bearings': ';'.join(self._encode_bearing(b) for b in bearings)})
profile_ns, profile_name = profile.split('/')
uri = URITemplate(
self.baseuri + '/{profile_ns}/{profile_name}/{coordinates}.json').expand(
profile_ns=profile_ns, profile_name=profile_name, coordinates=coordinates)
resp = self.session.get(uri, params=params)
self.handle_http_error(resp)
def geojson():
return self._geojson(resp.json(), geom_format=geometries)
resp.geojson = geojson
return resp | python | def directions(self, features, profile='mapbox/driving',
alternatives=None, geometries=None, overview=None, steps=None,
continue_straight=None, waypoint_snapping=None, annotations=None,
language=None, **kwargs):
"""Request directions for waypoints encoded as GeoJSON features.
Parameters
----------
features : iterable
An collection of GeoJSON features
profile : str
Name of a Mapbox profile such as 'mapbox.driving'
alternatives : bool
Whether to try to return alternative routes, default: False
geometries : string
Type of geometry returned (geojson, polyline, polyline6)
overview : string or False
Type of returned overview geometry: 'full', 'simplified',
or False
steps : bool
Whether to return steps and turn-by-turn instructions,
default: False
continue_straight : bool
Direction of travel when departing intermediate waypoints
radiuses : iterable of numbers or 'unlimited'
Must be same length as features
waypoint_snapping : list
Controls snapping of waypoints
The list is zipped with the features collection and must
have the same length. Elements of the list must be one of:
- A number (interpretted as a snapping radius)
- The string 'unlimited' (unlimited snapping radius)
- A 3-element tuple consisting of (radius, angle, range)
- None (no snapping parameters specified for that waypoint)
annotations : str
Whether or not to return additional metadata along the route
Possible values are: 'duration', 'distance', 'speed', and
'congestion'. Several annotations can be used by joining
them with ','.
language : str
Language of returned turn-by-turn text instructions,
default: 'en'
Returns
-------
requests.Response
The response object has a geojson() method for access to
the route(s) as a GeoJSON-like FeatureCollection
dictionary.
"""
# backwards compatible, deprecated
if 'geometry' in kwargs and geometries is None:
geometries = kwargs['geometry']
warnings.warn('Use `geometries` instead of `geometry`',
errors.MapboxDeprecationWarning)
annotations = self._validate_annotations(annotations)
coordinates = encode_coordinates(
features, precision=6, min_limit=2, max_limit=25)
geometries = self._validate_geom_encoding(geometries)
overview = self._validate_geom_overview(overview)
profile = self._validate_profile(profile)
bearings, radii = self._validate_snapping(waypoint_snapping, features)
params = {}
if alternatives is not None:
params.update(
{'alternatives': 'true' if alternatives is True else 'false'})
if geometries is not None:
params.update({'geometries': geometries})
if overview is not None:
params.update(
{'overview': 'false' if overview is False else overview})
if steps is not None:
params.update(
{'steps': 'true' if steps is True else 'false'})
if continue_straight is not None:
params.update(
{'continue_straight': 'true' if steps is True else 'false'})
if annotations is not None:
params.update({'annotations': ','.join(annotations)})
if language is not None:
params.update({'language': language})
if radii is not None:
params.update(
{'radiuses': ';'.join(str(r) for r in radii)})
if bearings is not None:
params.update(
{'bearings': ';'.join(self._encode_bearing(b) for b in bearings)})
profile_ns, profile_name = profile.split('/')
uri = URITemplate(
self.baseuri + '/{profile_ns}/{profile_name}/{coordinates}.json').expand(
profile_ns=profile_ns, profile_name=profile_name, coordinates=coordinates)
resp = self.session.get(uri, params=params)
self.handle_http_error(resp)
def geojson():
return self._geojson(resp.json(), geom_format=geometries)
resp.geojson = geojson
return resp | [
"def",
"directions",
"(",
"self",
",",
"features",
",",
"profile",
"=",
"'mapbox/driving'",
",",
"alternatives",
"=",
"None",
",",
"geometries",
"=",
"None",
",",
"overview",
"=",
"None",
",",
"steps",
"=",
"None",
",",
"continue_straight",
"=",
"None",
",... | Request directions for waypoints encoded as GeoJSON features.
Parameters
----------
features : iterable
An collection of GeoJSON features
profile : str
Name of a Mapbox profile such as 'mapbox.driving'
alternatives : bool
Whether to try to return alternative routes, default: False
geometries : string
Type of geometry returned (geojson, polyline, polyline6)
overview : string or False
Type of returned overview geometry: 'full', 'simplified',
or False
steps : bool
Whether to return steps and turn-by-turn instructions,
default: False
continue_straight : bool
Direction of travel when departing intermediate waypoints
radiuses : iterable of numbers or 'unlimited'
Must be same length as features
waypoint_snapping : list
Controls snapping of waypoints
The list is zipped with the features collection and must
have the same length. Elements of the list must be one of:
- A number (interpretted as a snapping radius)
- The string 'unlimited' (unlimited snapping radius)
- A 3-element tuple consisting of (radius, angle, range)
- None (no snapping parameters specified for that waypoint)
annotations : str
Whether or not to return additional metadata along the route
Possible values are: 'duration', 'distance', 'speed', and
'congestion'. Several annotations can be used by joining
them with ','.
language : str
Language of returned turn-by-turn text instructions,
default: 'en'
Returns
-------
requests.Response
The response object has a geojson() method for access to
the route(s) as a GeoJSON-like FeatureCollection
dictionary. | [
"Request",
"directions",
"for",
"waypoints",
"encoded",
"as",
"GeoJSON",
"features",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/directions.py#L143-L249 | train | 219,779 |
mapbox/mapbox-sdk-py | mapbox/services/matrix.py | DirectionsMatrix.matrix | def matrix(self, coordinates, profile='mapbox/driving',
sources=None, destinations=None, annotations=None):
"""Request a directions matrix for trips between coordinates
In the default case, the matrix returns a symmetric matrix,
using all input coordinates as sources and destinations. You may
also generate an asymmetric matrix, with only some coordinates
as sources or destinations:
Parameters
----------
coordinates : sequence
A sequence of coordinates, which may be represented as
GeoJSON features, GeoJSON geometries, or (longitude,
latitude) pairs.
profile : str
The trip travel mode. Valid modes are listed in the class's
valid_profiles attribute.
annotations : list
Used to specify the resulting matrices. Possible values are
listed in the class's valid_annotations attribute.
sources : list
Indices of source coordinates to include in the matrix.
Default is all coordinates.
destinations : list
Indices of destination coordinates to include in the
matrix. Default is all coordinates.
Returns
-------
requests.Response
Note: the directions matrix itself is obtained by calling the
response's json() method. The resulting mapping has a code,
the destinations and the sources, and depending of the
annotations specified, it can also contain a durations matrix,
a distances matrix or both of them (by default, only the
durations matrix is provided).
code : str
Status of the response
sources : list
Results of snapping selected coordinates to the nearest
addresses.
destinations : list
Results of snapping selected coordinates to the nearest
addresses.
durations : list
An array of arrays representing the matrix in row-major
order. durations[i][j] gives the travel time from the i-th
source to the j-th destination. All values are in seconds.
The duration between the same coordinate is always 0. If
a duration can not be found, the result is null.
distances : list
An array of arrays representing the matrix in row-major
order. distances[i][j] gives the distance from the i-th
source to the j-th destination. All values are in meters.
The distance between the same coordinate is always 0. If
a distance can not be found, the result is null.
"""
annotations = self._validate_annotations(annotations)
profile = self._validate_profile(profile)
coords = encode_waypoints(coordinates)
params = self._make_query(sources, destinations)
if annotations is not None:
params.update({'annotations': ','.join(annotations)})
uri = '{0}/{1}/{2}'.format(self.baseuri, profile, coords)
res = self.session.get(uri, params=params)
self.handle_http_error(res)
return res | python | def matrix(self, coordinates, profile='mapbox/driving',
sources=None, destinations=None, annotations=None):
"""Request a directions matrix for trips between coordinates
In the default case, the matrix returns a symmetric matrix,
using all input coordinates as sources and destinations. You may
also generate an asymmetric matrix, with only some coordinates
as sources or destinations:
Parameters
----------
coordinates : sequence
A sequence of coordinates, which may be represented as
GeoJSON features, GeoJSON geometries, or (longitude,
latitude) pairs.
profile : str
The trip travel mode. Valid modes are listed in the class's
valid_profiles attribute.
annotations : list
Used to specify the resulting matrices. Possible values are
listed in the class's valid_annotations attribute.
sources : list
Indices of source coordinates to include in the matrix.
Default is all coordinates.
destinations : list
Indices of destination coordinates to include in the
matrix. Default is all coordinates.
Returns
-------
requests.Response
Note: the directions matrix itself is obtained by calling the
response's json() method. The resulting mapping has a code,
the destinations and the sources, and depending of the
annotations specified, it can also contain a durations matrix,
a distances matrix or both of them (by default, only the
durations matrix is provided).
code : str
Status of the response
sources : list
Results of snapping selected coordinates to the nearest
addresses.
destinations : list
Results of snapping selected coordinates to the nearest
addresses.
durations : list
An array of arrays representing the matrix in row-major
order. durations[i][j] gives the travel time from the i-th
source to the j-th destination. All values are in seconds.
The duration between the same coordinate is always 0. If
a duration can not be found, the result is null.
distances : list
An array of arrays representing the matrix in row-major
order. distances[i][j] gives the distance from the i-th
source to the j-th destination. All values are in meters.
The distance between the same coordinate is always 0. If
a distance can not be found, the result is null.
"""
annotations = self._validate_annotations(annotations)
profile = self._validate_profile(profile)
coords = encode_waypoints(coordinates)
params = self._make_query(sources, destinations)
if annotations is not None:
params.update({'annotations': ','.join(annotations)})
uri = '{0}/{1}/{2}'.format(self.baseuri, profile, coords)
res = self.session.get(uri, params=params)
self.handle_http_error(res)
return res | [
"def",
"matrix",
"(",
"self",
",",
"coordinates",
",",
"profile",
"=",
"'mapbox/driving'",
",",
"sources",
"=",
"None",
",",
"destinations",
"=",
"None",
",",
"annotations",
"=",
"None",
")",
":",
"annotations",
"=",
"self",
".",
"_validate_annotations",
"("... | Request a directions matrix for trips between coordinates
In the default case, the matrix returns a symmetric matrix,
using all input coordinates as sources and destinations. You may
also generate an asymmetric matrix, with only some coordinates
as sources or destinations:
Parameters
----------
coordinates : sequence
A sequence of coordinates, which may be represented as
GeoJSON features, GeoJSON geometries, or (longitude,
latitude) pairs.
profile : str
The trip travel mode. Valid modes are listed in the class's
valid_profiles attribute.
annotations : list
Used to specify the resulting matrices. Possible values are
listed in the class's valid_annotations attribute.
sources : list
Indices of source coordinates to include in the matrix.
Default is all coordinates.
destinations : list
Indices of destination coordinates to include in the
matrix. Default is all coordinates.
Returns
-------
requests.Response
Note: the directions matrix itself is obtained by calling the
response's json() method. The resulting mapping has a code,
the destinations and the sources, and depending of the
annotations specified, it can also contain a durations matrix,
a distances matrix or both of them (by default, only the
durations matrix is provided).
code : str
Status of the response
sources : list
Results of snapping selected coordinates to the nearest
addresses.
destinations : list
Results of snapping selected coordinates to the nearest
addresses.
durations : list
An array of arrays representing the matrix in row-major
order. durations[i][j] gives the travel time from the i-th
source to the j-th destination. All values are in seconds.
The duration between the same coordinate is always 0. If
a duration can not be found, the result is null.
distances : list
An array of arrays representing the matrix in row-major
order. distances[i][j] gives the distance from the i-th
source to the j-th destination. All values are in meters.
The distance between the same coordinate is always 0. If
a distance can not be found, the result is null. | [
"Request",
"a",
"directions",
"matrix",
"for",
"trips",
"between",
"coordinates"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/matrix.py#L65-L138 | train | 219,780 |
mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets._attribs | def _attribs(self, name=None, description=None):
"""Form an attributes dictionary from keyword args."""
a = {}
if name:
a['name'] = name
if description:
a['description'] = description
return a | python | def _attribs(self, name=None, description=None):
"""Form an attributes dictionary from keyword args."""
a = {}
if name:
a['name'] = name
if description:
a['description'] = description
return a | [
"def",
"_attribs",
"(",
"self",
",",
"name",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"a",
"=",
"{",
"}",
"if",
"name",
":",
"a",
"[",
"'name'",
"]",
"=",
"name",
"if",
"description",
":",
"a",
"[",
"'description'",
"]",
"=",
"desc... | Form an attributes dictionary from keyword args. | [
"Form",
"an",
"attributes",
"dictionary",
"from",
"keyword",
"args",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L25-L32 | train | 219,781 |
mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets.create | def create(self, name=None, description=None):
"""Creates a new, empty dataset.
Parameters
----------
name : str, optional
The name of the dataset.
description : str, optional
The description of the dataset.
Returns
-------
request.Response
The response contains the properties of a new dataset as a JSON object.
"""
uri = URITemplate(self.baseuri + '/{owner}').expand(
owner=self.username)
return self.session.post(uri, json=self._attribs(name, description)) | python | def create(self, name=None, description=None):
"""Creates a new, empty dataset.
Parameters
----------
name : str, optional
The name of the dataset.
description : str, optional
The description of the dataset.
Returns
-------
request.Response
The response contains the properties of a new dataset as a JSON object.
"""
uri = URITemplate(self.baseuri + '/{owner}').expand(
owner=self.username)
return self.session.post(uri, json=self._attribs(name, description)) | [
"def",
"create",
"(",
"self",
",",
"name",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{owner}'",
")",
".",
"expand",
"(",
"owner",
"=",
"self",
".",
"username",
")",
"return... | Creates a new, empty dataset.
Parameters
----------
name : str, optional
The name of the dataset.
description : str, optional
The description of the dataset.
Returns
-------
request.Response
The response contains the properties of a new dataset as a JSON object. | [
"Creates",
"a",
"new",
"empty",
"dataset",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L34-L53 | train | 219,782 |
mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets.list | def list(self):
"""Lists all datasets for a particular account.
Returns
-------
request.Response
The response contains a list of JSON objects describing datasets.
"""
uri = URITemplate(self.baseuri + '/{owner}').expand(
owner=self.username)
return self.session.get(uri) | python | def list(self):
"""Lists all datasets for a particular account.
Returns
-------
request.Response
The response contains a list of JSON objects describing datasets.
"""
uri = URITemplate(self.baseuri + '/{owner}').expand(
owner=self.username)
return self.session.get(uri) | [
"def",
"list",
"(",
"self",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{owner}'",
")",
".",
"expand",
"(",
"owner",
"=",
"self",
".",
"username",
")",
"return",
"self",
".",
"session",
".",
"get",
"(",
"uri",
")"
] | Lists all datasets for a particular account.
Returns
-------
request.Response
The response contains a list of JSON objects describing datasets. | [
"Lists",
"all",
"datasets",
"for",
"a",
"particular",
"account",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L55-L66 | train | 219,783 |
mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets.update_dataset | def update_dataset(self, dataset, name=None, description=None):
"""Updates a single dataset.
Parameters
----------
dataset : str
The dataset id.
name : str, optional
The name of the dataset.
description : str, optional
The description of the dataset.
Returns
-------
request.Response
The response contains the properties of the updated dataset as a JSON object.
"""
uri = URITemplate(self.baseuri + '/{owner}/{id}').expand(
owner=self.username, id=dataset)
return self.session.patch(uri, json=self._attribs(name, description)) | python | def update_dataset(self, dataset, name=None, description=None):
"""Updates a single dataset.
Parameters
----------
dataset : str
The dataset id.
name : str, optional
The name of the dataset.
description : str, optional
The description of the dataset.
Returns
-------
request.Response
The response contains the properties of the updated dataset as a JSON object.
"""
uri = URITemplate(self.baseuri + '/{owner}/{id}').expand(
owner=self.username, id=dataset)
return self.session.patch(uri, json=self._attribs(name, description)) | [
"def",
"update_dataset",
"(",
"self",
",",
"dataset",
",",
"name",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{owner}/{id}'",
")",
".",
"expand",
"(",
"owner",
"=",
"self",
".... | Updates a single dataset.
Parameters
----------
dataset : str
The dataset id.
name : str, optional
The name of the dataset.
description : str, optional
The description of the dataset.
Returns
-------
request.Response
The response contains the properties of the updated dataset as a JSON object. | [
"Updates",
"a",
"single",
"dataset",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L86-L108 | train | 219,784 |
mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets.delete_dataset | def delete_dataset(self, dataset):
"""Deletes a single dataset, including all of the features that it contains.
Parameters
----------
dataset : str
The dataset id.
Returns
-------
HTTP status code.
"""
uri = URITemplate(self.baseuri + '/{owner}/{id}').expand(
owner=self.username, id=dataset)
return self.session.delete(uri) | python | def delete_dataset(self, dataset):
"""Deletes a single dataset, including all of the features that it contains.
Parameters
----------
dataset : str
The dataset id.
Returns
-------
HTTP status code.
"""
uri = URITemplate(self.baseuri + '/{owner}/{id}').expand(
owner=self.username, id=dataset)
return self.session.delete(uri) | [
"def",
"delete_dataset",
"(",
"self",
",",
"dataset",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{owner}/{id}'",
")",
".",
"expand",
"(",
"owner",
"=",
"self",
".",
"username",
",",
"id",
"=",
"dataset",
")",
"return",
"s... | Deletes a single dataset, including all of the features that it contains.
Parameters
----------
dataset : str
The dataset id.
Returns
-------
HTTP status code. | [
"Deletes",
"a",
"single",
"dataset",
"including",
"all",
"of",
"the",
"features",
"that",
"it",
"contains",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L110-L125 | train | 219,785 |
mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets.list_features | def list_features(self, dataset, reverse=False, start=None, limit=None):
"""Lists features in a dataset.
Parameters
----------
dataset : str
The dataset id.
reverse : str, optional
List features in reverse order.
Possible value is "true".
start : str, optional
The id of the feature after which to start the list (pagination).
limit : str, optional
The maximum number of features to list (pagination).
Returns
-------
request.Response
The response contains the features of a dataset as a GeoJSON FeatureCollection.
"""
uri = URITemplate(self.baseuri + '/{owner}/{id}/features').expand(
owner=self.username, id=dataset)
params = {}
if reverse:
params['reverse'] = 'true'
if start:
params['start'] = start
if limit:
params['limit'] = int(limit)
return self.session.get(uri, params=params) | python | def list_features(self, dataset, reverse=False, start=None, limit=None):
"""Lists features in a dataset.
Parameters
----------
dataset : str
The dataset id.
reverse : str, optional
List features in reverse order.
Possible value is "true".
start : str, optional
The id of the feature after which to start the list (pagination).
limit : str, optional
The maximum number of features to list (pagination).
Returns
-------
request.Response
The response contains the features of a dataset as a GeoJSON FeatureCollection.
"""
uri = URITemplate(self.baseuri + '/{owner}/{id}/features').expand(
owner=self.username, id=dataset)
params = {}
if reverse:
params['reverse'] = 'true'
if start:
params['start'] = start
if limit:
params['limit'] = int(limit)
return self.session.get(uri, params=params) | [
"def",
"list_features",
"(",
"self",
",",
"dataset",
",",
"reverse",
"=",
"False",
",",
"start",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{owner}/{id}/features'",
")",
".",
"expand"... | Lists features in a dataset.
Parameters
----------
dataset : str
The dataset id.
reverse : str, optional
List features in reverse order.
Possible value is "true".
start : str, optional
The id of the feature after which to start the list (pagination).
limit : str, optional
The maximum number of features to list (pagination).
Returns
-------
request.Response
The response contains the features of a dataset as a GeoJSON FeatureCollection. | [
"Lists",
"features",
"in",
"a",
"dataset",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L127-L162 | train | 219,786 |
mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets.delete_feature | def delete_feature(self, dataset, fid):
"""Removes a feature from a dataset.
Parameters
----------
dataset : str
The dataset id.
fid : str
The feature id.
Returns
-------
HTTP status code.
"""
uri = URITemplate(
self.baseuri + '/{owner}/{did}/features/{fid}').expand(
owner=self.username, did=dataset, fid=fid)
return self.session.delete(uri) | python | def delete_feature(self, dataset, fid):
"""Removes a feature from a dataset.
Parameters
----------
dataset : str
The dataset id.
fid : str
The feature id.
Returns
-------
HTTP status code.
"""
uri = URITemplate(
self.baseuri + '/{owner}/{did}/features/{fid}').expand(
owner=self.username, did=dataset, fid=fid)
return self.session.delete(uri) | [
"def",
"delete_feature",
"(",
"self",
",",
"dataset",
",",
"fid",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{owner}/{did}/features/{fid}'",
")",
".",
"expand",
"(",
"owner",
"=",
"self",
".",
"username",
",",
"did",
"=",
"... | Removes a feature from a dataset.
Parameters
----------
dataset : str
The dataset id.
fid : str
The feature id.
Returns
-------
HTTP status code. | [
"Removes",
"a",
"feature",
"from",
"a",
"dataset",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L217-L236 | train | 219,787 |
mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader._get_credentials | def _get_credentials(self):
"""Gets temporary S3 credentials to stage user-uploaded files
"""
uri = URITemplate(self.baseuri + '/{username}/credentials').expand(
username=self.username)
resp = self.session.post(uri)
self.handle_http_error(
resp,
custom_messages={
401: "Token is not authorized",
404: "Token does not have upload scope",
429: "Too many requests"})
return resp | python | def _get_credentials(self):
"""Gets temporary S3 credentials to stage user-uploaded files
"""
uri = URITemplate(self.baseuri + '/{username}/credentials').expand(
username=self.username)
resp = self.session.post(uri)
self.handle_http_error(
resp,
custom_messages={
401: "Token is not authorized",
404: "Token does not have upload scope",
429: "Too many requests"})
return resp | [
"def",
"_get_credentials",
"(",
"self",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{username}/credentials'",
")",
".",
"expand",
"(",
"username",
"=",
"self",
".",
"username",
")",
"resp",
"=",
"self",
".",
"session",
".",
... | Gets temporary S3 credentials to stage user-uploaded files | [
"Gets",
"temporary",
"S3",
"credentials",
"to",
"stage",
"user",
"-",
"uploaded",
"files"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L37-L51 | train | 219,788 |
mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader._validate_tileset | def _validate_tileset(self, tileset):
"""Validate the tileset name and
ensure that it includes the username
"""
if '.' not in tileset:
tileset = "{0}.{1}".format(self.username, tileset)
pattern = '^[a-z0-9-_]{1,32}\.[a-z0-9-_]{1,32}$'
if not re.match(pattern, tileset, flags=re.IGNORECASE):
raise ValidationError(
'tileset {0} is invalid, must match r"{1}"'.format(
tileset, pattern))
return tileset | python | def _validate_tileset(self, tileset):
"""Validate the tileset name and
ensure that it includes the username
"""
if '.' not in tileset:
tileset = "{0}.{1}".format(self.username, tileset)
pattern = '^[a-z0-9-_]{1,32}\.[a-z0-9-_]{1,32}$'
if not re.match(pattern, tileset, flags=re.IGNORECASE):
raise ValidationError(
'tileset {0} is invalid, must match r"{1}"'.format(
tileset, pattern))
return tileset | [
"def",
"_validate_tileset",
"(",
"self",
",",
"tileset",
")",
":",
"if",
"'.'",
"not",
"in",
"tileset",
":",
"tileset",
"=",
"\"{0}.{1}\"",
".",
"format",
"(",
"self",
".",
"username",
",",
"tileset",
")",
"pattern",
"=",
"'^[a-z0-9-_]{1,32}\\.[a-z0-9-_]{1,32}... | Validate the tileset name and
ensure that it includes the username | [
"Validate",
"the",
"tileset",
"name",
"and",
"ensure",
"that",
"it",
"includes",
"the",
"username"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L53-L66 | train | 219,789 |
mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader._resolve_username | def _resolve_username(self, account, username):
"""Resolve username and handle deprecation of account kwarg"""
if account is not None:
warnings.warn(
"Use keyword argument 'username' instead of 'account'",
DeprecationWarning)
return username or account or self.username | python | def _resolve_username(self, account, username):
"""Resolve username and handle deprecation of account kwarg"""
if account is not None:
warnings.warn(
"Use keyword argument 'username' instead of 'account'",
DeprecationWarning)
return username or account or self.username | [
"def",
"_resolve_username",
"(",
"self",
",",
"account",
",",
"username",
")",
":",
"if",
"account",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"Use keyword argument 'username' instead of 'account'\"",
",",
"DeprecationWarning",
")",
"return",
"userna... | Resolve username and handle deprecation of account kwarg | [
"Resolve",
"username",
"and",
"handle",
"deprecation",
"of",
"account",
"kwarg"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L69-L75 | train | 219,790 |
mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader.stage | def stage(self, fileobj, creds=None, callback=None):
"""Stages data in a Mapbox-owned S3 bucket
If creds are not provided, temporary credentials will be
generated using the Mapbox API.
Parameters
----------
fileobj: file object or filename
A Python file object opened in binary mode or a filename.
creds: dict
AWS credentials allowing uploads to the destination bucket.
callback: func
A function that takes a number of bytes processed as its
sole argument.
Returns
-------
str
The URL of the staged data
"""
if not hasattr(fileobj, 'read'):
fileobj = open(fileobj, 'rb')
if not creds:
res = self._get_credentials()
creds = res.json()
session = boto3_session(
aws_access_key_id=creds['accessKeyId'],
aws_secret_access_key=creds['secretAccessKey'],
aws_session_token=creds['sessionToken'],
region_name='us-east-1')
s3 = session.resource('s3')
bucket = s3.Bucket(creds['bucket'])
key = creds['key']
bucket.upload_fileobj(fileobj, key, Callback=callback)
return creds['url'] | python | def stage(self, fileobj, creds=None, callback=None):
"""Stages data in a Mapbox-owned S3 bucket
If creds are not provided, temporary credentials will be
generated using the Mapbox API.
Parameters
----------
fileobj: file object or filename
A Python file object opened in binary mode or a filename.
creds: dict
AWS credentials allowing uploads to the destination bucket.
callback: func
A function that takes a number of bytes processed as its
sole argument.
Returns
-------
str
The URL of the staged data
"""
if not hasattr(fileobj, 'read'):
fileobj = open(fileobj, 'rb')
if not creds:
res = self._get_credentials()
creds = res.json()
session = boto3_session(
aws_access_key_id=creds['accessKeyId'],
aws_secret_access_key=creds['secretAccessKey'],
aws_session_token=creds['sessionToken'],
region_name='us-east-1')
s3 = session.resource('s3')
bucket = s3.Bucket(creds['bucket'])
key = creds['key']
bucket.upload_fileobj(fileobj, key, Callback=callback)
return creds['url'] | [
"def",
"stage",
"(",
"self",
",",
"fileobj",
",",
"creds",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"fileobj",
",",
"'read'",
")",
":",
"fileobj",
"=",
"open",
"(",
"fileobj",
",",
"'rb'",
")",
"if",
"not",
... | Stages data in a Mapbox-owned S3 bucket
If creds are not provided, temporary credentials will be
generated using the Mapbox API.
Parameters
----------
fileobj: file object or filename
A Python file object opened in binary mode or a filename.
creds: dict
AWS credentials allowing uploads to the destination bucket.
callback: func
A function that takes a number of bytes processed as its
sole argument.
Returns
-------
str
The URL of the staged data | [
"Stages",
"data",
"in",
"a",
"Mapbox",
"-",
"owned",
"S3",
"bucket"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L77-L117 | train | 219,791 |
mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader.create | def create(self, stage_url, tileset, name=None, patch=False, bypass=False):
"""Create a tileset
Note: this step is refered to as "upload" in the API docs;
This class's upload() method is a high-level function
which acts like the Studio upload form.
Returns a response object where the json() contents are
an upload dict. Completion of the tileset may take several
seconds or minutes depending on size of the data. The status()
method of this class may be used to poll the API endpoint for
tileset creation status.
Parameters
----------
stage_url: str
URL to resource on S3, typically provided in the response
of this class's stage() method.
tileset: str
The id of the tileset set to be created. Username will be
prefixed if not present. For example, 'my-tileset' becomes
'{username}.my-tileset'.
name: str
A short name for the tileset that will appear in Mapbox
studio.
patch: bool
Optional patch mode which requires a flag on the owner's
account.
bypass: bool
Optional bypass validation mode for MBTiles which requires
a flag on the owner's account.
Returns
-------
requests.Response
"""
tileset = self._validate_tileset(tileset)
username, _name = tileset.split(".")
msg = {'tileset': tileset,
'url': stage_url}
if patch:
msg['patch'] = patch
if bypass:
msg['bypass_mbtiles_validation'] = bypass
msg['name'] = name if name else _name
uri = URITemplate(self.baseuri + '/{username}').expand(
username=username)
resp = self.session.post(uri, json=msg)
self.handle_http_error(resp)
return resp | python | def create(self, stage_url, tileset, name=None, patch=False, bypass=False):
"""Create a tileset
Note: this step is refered to as "upload" in the API docs;
This class's upload() method is a high-level function
which acts like the Studio upload form.
Returns a response object where the json() contents are
an upload dict. Completion of the tileset may take several
seconds or minutes depending on size of the data. The status()
method of this class may be used to poll the API endpoint for
tileset creation status.
Parameters
----------
stage_url: str
URL to resource on S3, typically provided in the response
of this class's stage() method.
tileset: str
The id of the tileset set to be created. Username will be
prefixed if not present. For example, 'my-tileset' becomes
'{username}.my-tileset'.
name: str
A short name for the tileset that will appear in Mapbox
studio.
patch: bool
Optional patch mode which requires a flag on the owner's
account.
bypass: bool
Optional bypass validation mode for MBTiles which requires
a flag on the owner's account.
Returns
-------
requests.Response
"""
tileset = self._validate_tileset(tileset)
username, _name = tileset.split(".")
msg = {'tileset': tileset,
'url': stage_url}
if patch:
msg['patch'] = patch
if bypass:
msg['bypass_mbtiles_validation'] = bypass
msg['name'] = name if name else _name
uri = URITemplate(self.baseuri + '/{username}').expand(
username=username)
resp = self.session.post(uri, json=msg)
self.handle_http_error(resp)
return resp | [
"def",
"create",
"(",
"self",
",",
"stage_url",
",",
"tileset",
",",
"name",
"=",
"None",
",",
"patch",
"=",
"False",
",",
"bypass",
"=",
"False",
")",
":",
"tileset",
"=",
"self",
".",
"_validate_tileset",
"(",
"tileset",
")",
"username",
",",
"_name"... | Create a tileset
Note: this step is refered to as "upload" in the API docs;
This class's upload() method is a high-level function
which acts like the Studio upload form.
Returns a response object where the json() contents are
an upload dict. Completion of the tileset may take several
seconds or minutes depending on size of the data. The status()
method of this class may be used to poll the API endpoint for
tileset creation status.
Parameters
----------
stage_url: str
URL to resource on S3, typically provided in the response
of this class's stage() method.
tileset: str
The id of the tileset set to be created. Username will be
prefixed if not present. For example, 'my-tileset' becomes
'{username}.my-tileset'.
name: str
A short name for the tileset that will appear in Mapbox
studio.
patch: bool
Optional patch mode which requires a flag on the owner's
account.
bypass: bool
Optional bypass validation mode for MBTiles which requires
a flag on the owner's account.
Returns
-------
requests.Response | [
"Create",
"a",
"tileset"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L119-L175 | train | 219,792 |
mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader.list | def list(self, account=None, username=None):
"""List of all uploads
Returns a Response object, the json() method of which returns
a list of uploads
Parameters
----------
username : str
Account username, defaults to the service's username.
account : str, **deprecated**
Alias for username. Will be removed in version 1.0.
Returns
-------
requests.Response
"""
username = self._resolve_username(account, username)
uri = URITemplate(self.baseuri + '/{username}').expand(
username=username)
resp = self.session.get(uri)
self.handle_http_error(resp)
return resp | python | def list(self, account=None, username=None):
"""List of all uploads
Returns a Response object, the json() method of which returns
a list of uploads
Parameters
----------
username : str
Account username, defaults to the service's username.
account : str, **deprecated**
Alias for username. Will be removed in version 1.0.
Returns
-------
requests.Response
"""
username = self._resolve_username(account, username)
uri = URITemplate(self.baseuri + '/{username}').expand(
username=username)
resp = self.session.get(uri)
self.handle_http_error(resp)
return resp | [
"def",
"list",
"(",
"self",
",",
"account",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"username",
"=",
"self",
".",
"_resolve_username",
"(",
"account",
",",
"username",
")",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{u... | List of all uploads
Returns a Response object, the json() method of which returns
a list of uploads
Parameters
----------
username : str
Account username, defaults to the service's username.
account : str, **deprecated**
Alias for username. Will be removed in version 1.0.
Returns
-------
requests.Response | [
"List",
"of",
"all",
"uploads"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L177-L199 | train | 219,793 |
mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader.status | def status(self, upload, account=None, username=None):
"""Check status of upload
Parameters
----------
upload: str
The id of the upload or a dict with key 'id'.
username : str
Account username, defaults to the service's username.
account : str, **deprecated**
Alias for username. Will be removed in version 1.0.
Returns
-------
requests.Response
"""
username = self._resolve_username(account, username)
if isinstance(upload, dict):
upload_id = upload['id']
else:
upload_id = upload
uri = URITemplate(self.baseuri + '/{username}/{upload_id}').expand(
username=username, upload_id=upload_id)
resp = self.session.get(uri)
self.handle_http_error(resp)
return resp | python | def status(self, upload, account=None, username=None):
"""Check status of upload
Parameters
----------
upload: str
The id of the upload or a dict with key 'id'.
username : str
Account username, defaults to the service's username.
account : str, **deprecated**
Alias for username. Will be removed in version 1.0.
Returns
-------
requests.Response
"""
username = self._resolve_username(account, username)
if isinstance(upload, dict):
upload_id = upload['id']
else:
upload_id = upload
uri = URITemplate(self.baseuri + '/{username}/{upload_id}').expand(
username=username, upload_id=upload_id)
resp = self.session.get(uri)
self.handle_http_error(resp)
return resp | [
"def",
"status",
"(",
"self",
",",
"upload",
",",
"account",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"username",
"=",
"self",
".",
"_resolve_username",
"(",
"account",
",",
"username",
")",
"if",
"isinstance",
"(",
"upload",
",",
"dict",
"... | Check status of upload
Parameters
----------
upload: str
The id of the upload or a dict with key 'id'.
username : str
Account username, defaults to the service's username.
account : str, **deprecated**
Alias for username. Will be removed in version 1.0.
Returns
-------
requests.Response | [
"Check",
"status",
"of",
"upload"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L228-L253 | train | 219,794 |
mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader.upload | def upload(self, fileobj, tileset, name=None, patch=False, callback=None, bypass=False):
"""Upload data and create a Mapbox tileset
Effectively replicates the Studio upload feature. Returns a
Response object, the json() of which returns a dict with upload
metadata.
Parameters
----------
fileobj: file object or str
A filename or a Python file object opened in binary mode.
tileset: str
A tileset identifier such as '{owner}.my-tileset'.
name: str
A short name for the tileset that will appear in Mapbox
studio.
patch: bool
Optional patch mode which requires a flag on the owner's
account.
bypass: bool
Optional bypass validation mode for MBTiles which requires
a flag on the owner's account.
callback: func
A function that takes a number of bytes processed as its
sole argument. May be used with a progress bar.
Returns
-------
requests.Response
"""
tileset = self._validate_tileset(tileset)
url = self.stage(fileobj, callback=callback)
return self.create(url, tileset, name=name, patch=patch, bypass=bypass) | python | def upload(self, fileobj, tileset, name=None, patch=False, callback=None, bypass=False):
"""Upload data and create a Mapbox tileset
Effectively replicates the Studio upload feature. Returns a
Response object, the json() of which returns a dict with upload
metadata.
Parameters
----------
fileobj: file object or str
A filename or a Python file object opened in binary mode.
tileset: str
A tileset identifier such as '{owner}.my-tileset'.
name: str
A short name for the tileset that will appear in Mapbox
studio.
patch: bool
Optional patch mode which requires a flag on the owner's
account.
bypass: bool
Optional bypass validation mode for MBTiles which requires
a flag on the owner's account.
callback: func
A function that takes a number of bytes processed as its
sole argument. May be used with a progress bar.
Returns
-------
requests.Response
"""
tileset = self._validate_tileset(tileset)
url = self.stage(fileobj, callback=callback)
return self.create(url, tileset, name=name, patch=patch, bypass=bypass) | [
"def",
"upload",
"(",
"self",
",",
"fileobj",
",",
"tileset",
",",
"name",
"=",
"None",
",",
"patch",
"=",
"False",
",",
"callback",
"=",
"None",
",",
"bypass",
"=",
"False",
")",
":",
"tileset",
"=",
"self",
".",
"_validate_tileset",
"(",
"tileset",
... | Upload data and create a Mapbox tileset
Effectively replicates the Studio upload feature. Returns a
Response object, the json() of which returns a dict with upload
metadata.
Parameters
----------
fileobj: file object or str
A filename or a Python file object opened in binary mode.
tileset: str
A tileset identifier such as '{owner}.my-tileset'.
name: str
A short name for the tileset that will appear in Mapbox
studio.
patch: bool
Optional patch mode which requires a flag on the owner's
account.
bypass: bool
Optional bypass validation mode for MBTiles which requires
a flag on the owner's account.
callback: func
A function that takes a number of bytes processed as its
sole argument. May be used with a progress bar.
Returns
-------
requests.Response | [
"Upload",
"data",
"and",
"create",
"a",
"Mapbox",
"tileset"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L255-L287 | train | 219,795 |
mapbox/mapbox-sdk-py | mapbox/services/geocoding.py | Geocoder._validate_country_codes | def _validate_country_codes(self, ccs):
"""Validate country code filters for use in requests."""
for cc in ccs:
if cc not in self.country_codes:
raise InvalidCountryCodeError(cc)
return {'country': ",".join(ccs)} | python | def _validate_country_codes(self, ccs):
"""Validate country code filters for use in requests."""
for cc in ccs:
if cc not in self.country_codes:
raise InvalidCountryCodeError(cc)
return {'country': ",".join(ccs)} | [
"def",
"_validate_country_codes",
"(",
"self",
",",
"ccs",
")",
":",
"for",
"cc",
"in",
"ccs",
":",
"if",
"cc",
"not",
"in",
"self",
".",
"country_codes",
":",
"raise",
"InvalidCountryCodeError",
"(",
"cc",
")",
"return",
"{",
"'country'",
":",
"\",\"",
... | Validate country code filters for use in requests. | [
"Validate",
"country",
"code",
"filters",
"for",
"use",
"in",
"requests",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/geocoding.py#L28-L33 | train | 219,796 |
mapbox/mapbox-sdk-py | mapbox/services/geocoding.py | Geocoder._validate_place_types | def _validate_place_types(self, types):
"""Validate place types and return a mapping for use in requests."""
for pt in types:
if pt not in self.place_types:
raise InvalidPlaceTypeError(pt)
return {'types': ",".join(types)} | python | def _validate_place_types(self, types):
"""Validate place types and return a mapping for use in requests."""
for pt in types:
if pt not in self.place_types:
raise InvalidPlaceTypeError(pt)
return {'types': ",".join(types)} | [
"def",
"_validate_place_types",
"(",
"self",
",",
"types",
")",
":",
"for",
"pt",
"in",
"types",
":",
"if",
"pt",
"not",
"in",
"self",
".",
"place_types",
":",
"raise",
"InvalidPlaceTypeError",
"(",
"pt",
")",
"return",
"{",
"'types'",
":",
"\",\"",
".",... | Validate place types and return a mapping for use in requests. | [
"Validate",
"place",
"types",
"and",
"return",
"a",
"mapping",
"for",
"use",
"in",
"requests",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/geocoding.py#L35-L40 | train | 219,797 |
mapbox/mapbox-sdk-py | mapbox/services/geocoding.py | Geocoder.forward | def forward(self, address, types=None, lon=None, lat=None,
country=None, bbox=None, limit=None, languages=None):
"""Returns a Requests response object that contains a GeoJSON
collection of places matching the given address.
`response.geojson()` returns the geocoding result as GeoJSON.
`response.status_code` returns the HTTP API status code.
Place results may be constrained to those of one or more types
or be biased toward a given longitude and latitude.
See: https://www.mapbox.com/api-documentation/search/#geocoding."""
uri = URITemplate(self.baseuri + '/{dataset}/{query}.json').expand(
dataset=self.name, query=address.encode('utf-8'))
params = {}
if country:
params.update(self._validate_country_codes(country))
if types:
params.update(self._validate_place_types(types))
if lon is not None and lat is not None:
params.update(proximity='{0},{1}'.format(
round(float(lon), self.precision.get('proximity', 3)),
round(float(lat), self.precision.get('proximity', 3))))
if languages:
params.update(language=','.join(languages))
if bbox is not None:
params.update(bbox='{0},{1},{2},{3}'.format(*bbox))
if limit is not None:
params.update(limit='{0}'.format(limit))
resp = self.session.get(uri, params=params)
self.handle_http_error(resp)
# for consistency with other services
def geojson():
return resp.json()
resp.geojson = geojson
return resp | python | def forward(self, address, types=None, lon=None, lat=None,
country=None, bbox=None, limit=None, languages=None):
"""Returns a Requests response object that contains a GeoJSON
collection of places matching the given address.
`response.geojson()` returns the geocoding result as GeoJSON.
`response.status_code` returns the HTTP API status code.
Place results may be constrained to those of one or more types
or be biased toward a given longitude and latitude.
See: https://www.mapbox.com/api-documentation/search/#geocoding."""
uri = URITemplate(self.baseuri + '/{dataset}/{query}.json').expand(
dataset=self.name, query=address.encode('utf-8'))
params = {}
if country:
params.update(self._validate_country_codes(country))
if types:
params.update(self._validate_place_types(types))
if lon is not None and lat is not None:
params.update(proximity='{0},{1}'.format(
round(float(lon), self.precision.get('proximity', 3)),
round(float(lat), self.precision.get('proximity', 3))))
if languages:
params.update(language=','.join(languages))
if bbox is not None:
params.update(bbox='{0},{1},{2},{3}'.format(*bbox))
if limit is not None:
params.update(limit='{0}'.format(limit))
resp = self.session.get(uri, params=params)
self.handle_http_error(resp)
# for consistency with other services
def geojson():
return resp.json()
resp.geojson = geojson
return resp | [
"def",
"forward",
"(",
"self",
",",
"address",
",",
"types",
"=",
"None",
",",
"lon",
"=",
"None",
",",
"lat",
"=",
"None",
",",
"country",
"=",
"None",
",",
"bbox",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"languages",
"=",
"None",
")",
":",... | Returns a Requests response object that contains a GeoJSON
collection of places matching the given address.
`response.geojson()` returns the geocoding result as GeoJSON.
`response.status_code` returns the HTTP API status code.
Place results may be constrained to those of one or more types
or be biased toward a given longitude and latitude.
See: https://www.mapbox.com/api-documentation/search/#geocoding. | [
"Returns",
"a",
"Requests",
"response",
"object",
"that",
"contains",
"a",
"GeoJSON",
"collection",
"of",
"places",
"matching",
"the",
"given",
"address",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/geocoding.py#L42-L79 | train | 219,798 |
mapbox/mapbox-sdk-py | mapbox/services/geocoding.py | Geocoder.reverse | def reverse(self, lon, lat, types=None, limit=None):
"""Returns a Requests response object that contains a GeoJSON
collection of places near the given longitude and latitude.
`response.geojson()` returns the geocoding result as GeoJSON.
`response.status_code` returns the HTTP API status code.
See: https://www.mapbox.com/api-documentation/search/#reverse-geocoding."""
uri = URITemplate(self.baseuri + '/{dataset}/{lon},{lat}.json').expand(
dataset=self.name,
lon=str(round(float(lon), self.precision.get('reverse', 5))),
lat=str(round(float(lat), self.precision.get('reverse', 5))))
params = {}
if types:
types = list(types)
params.update(self._validate_place_types(types))
if limit is not None:
if not types or len(types) != 1:
raise InvalidPlaceTypeError(
'Specify a single type when using limit with reverse geocoding')
params.update(limit='{0}'.format(limit))
resp = self.session.get(uri, params=params)
self.handle_http_error(resp)
# for consistency with other services
def geojson():
return resp.json()
resp.geojson = geojson
return resp | python | def reverse(self, lon, lat, types=None, limit=None):
"""Returns a Requests response object that contains a GeoJSON
collection of places near the given longitude and latitude.
`response.geojson()` returns the geocoding result as GeoJSON.
`response.status_code` returns the HTTP API status code.
See: https://www.mapbox.com/api-documentation/search/#reverse-geocoding."""
uri = URITemplate(self.baseuri + '/{dataset}/{lon},{lat}.json').expand(
dataset=self.name,
lon=str(round(float(lon), self.precision.get('reverse', 5))),
lat=str(round(float(lat), self.precision.get('reverse', 5))))
params = {}
if types:
types = list(types)
params.update(self._validate_place_types(types))
if limit is not None:
if not types or len(types) != 1:
raise InvalidPlaceTypeError(
'Specify a single type when using limit with reverse geocoding')
params.update(limit='{0}'.format(limit))
resp = self.session.get(uri, params=params)
self.handle_http_error(resp)
# for consistency with other services
def geojson():
return resp.json()
resp.geojson = geojson
return resp | [
"def",
"reverse",
"(",
"self",
",",
"lon",
",",
"lat",
",",
"types",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{dataset}/{lon},{lat}.json'",
")",
".",
"expand",
"(",
"dataset",
"="... | Returns a Requests response object that contains a GeoJSON
collection of places near the given longitude and latitude.
`response.geojson()` returns the geocoding result as GeoJSON.
`response.status_code` returns the HTTP API status code.
See: https://www.mapbox.com/api-documentation/search/#reverse-geocoding. | [
"Returns",
"a",
"Requests",
"response",
"object",
"that",
"contains",
"a",
"GeoJSON",
"collection",
"of",
"places",
"near",
"the",
"given",
"longitude",
"and",
"latitude",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/geocoding.py#L81-L113 | train | 219,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.